lunes, 5 de diciembre de 2016

My first post on Rust

Again...I'm learning a new programming language...and this time is the turn for Rust.


Rust is very nice and have some really interesting features like ownership and borrowing...and the syntax really reminds me of OCaml...which is really cool as well...

Right now I'm reading the official documentation, that it's pretty well done...so of course I did my Fibonacci numbers app...

fibonacci.rs
use std::io;

fn fib(num: i64, a: i64, b:i64) -> String{
 let mut result: String = "".to_string();
 let sum: i64 = a + b;
 let sum_str: &str = &sum.to_string();
 let a_str: &str = &a.to_string();
 let b_str: &str = &b.to_string();
 if a > 0 && num > 1 {
  result = result + sum_str + " " + &fib((num - 1), (a + b), a);
 }else if a == 0{
  result = "".to_string() + a_str + " " + b_str + " " + 
           sum_str + " " + &fib((num - 1), (a + b), b); 
 }
 result
}

fn main(){
 println!("Enter a number : ");
 let mut input_num = String::new();
 io::stdin().read_line(&mut input_num)
            .expect("failed to read");

 let trimmed = input_num.trim();
    match trimmed.parse::() {
        Ok(i) => { let result: String = fib(i, 0, 1); print!("{}", result);}
        Err(..) => println!("Please enter an interger, not {}", trimmed)
    };
}

The code is a little bit long for my taste...but that might be simply because I haven't learned enough Rust...or because their ownership/borrowing system sacrifices length to add security...which is actually a pretty good thing...

Here's the result...



My LED Numbers app is ready of course...so it's coming right after this post -;)

Greetings,

Blag.
Development Culture.

No hay comentarios: