Hi, newbie Rust programmer, self-studying with the book. At the uni I used to program in C and I sort of could handle Java but for most of my working life ABAP has been my bread and butter.
I just finished writing the recommended examples at the end of chapter 3, the temperature conversion and the Fibonacci generator.
I struggled a bit with parsing the temperature, because I was attempting to be more general than strictly required for the example and ended up in deeper waters than my limited knowledge of the language can deal with. So I went for a fixed format and it works.
use std::io;
fn main() {
loop {
println!("Please enter temperature to be converted:");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let input = input.trim();
if input.is_empty() {
break;
};
let (temp, scale) = input.split_at(input.len() - 1);
let temperature: f64 = match temp.parse() {
Ok(temp) => temp,
Err(_) => continue,
};
match scale {
"C" => println!("{}C is {}F", temperature, (temperature * 9.0 / 5.0 + 32.0)),
"F" => println!("{}F is {}C", temperature, (temperature - 32.0) * 5.0 / 9.0),
_ => println!("No unit"),
}
}
}
I had considerably less difficulty with the Fibonacci generator:
use std::io;
fn fibonacci(index: i32) -> i32 {
match index {
0 => 0,
1 => 1,
_ => fibonacci(index - 1) + fibonacci(index - 2),
}
}
fn main() {
loop {
println!("Which N-th Fibonacci number?");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let input = input.trim();
if input.is_empty() {
break;
};
let fib_index: i32 = match input.parse() {
Ok(fib_index) => fib_index,
Err(_) => continue,
};
println!(
"The {fib_index}° Fibonacci number is {}",
fibonacci(fib_index)
);
}
}
Given that both programs work, what could still be improved? Any bad non-Rusty habits to break?
(the formatting is automatically applied when saving, because I am that lazy )
Thanks in advance,
Andrea.