I've been doing these exercises in order to learn Rust and I have a doubt about returning types. Lots of these exercises ask for an input from the user in order to do something. The main problem I've encountered has to to with the std::io module. One of these exercises asks for a year and the salary. Since I want to read the year as a i32 value and the salary as a f32 value I have come up with something like this. In case of the salary,
fn read_f32() -> f32 {
let mut s = String::new();
io::stdin().read_line(&mut s).expect("Cannot parse line");
let nb1 = match s.trim().parse::().expect("Cannot parse as f32 value");
nb1
}
And I did the same for the i32 value, only changing the f32 type to i32.
Is there a way to avoid having a function for each type?
I mean, to have something that returns a f64 when a f64 is needed, a i32 when one is needed and a &'static str when one is needed.......etc
Thanks
Fabrex
Ps: Any suggestions on improving the code I gave would be welcome and great for my learning process.
str::parse is generic over any type that implements FromStr, so you can do the same for your function:
use std::io;
use std::str::FromStr;
fn read_value<T: FromStr>() -> Result<T, <T as FromStr>::Err> {
let mut s = String::new();
io::stdin().read_line(&mut s).expect("could not read from stdin");
s.trim().parse()
}
Any suggestions on improving the code I gave would be welcome and great for my learning process.
Stop munging so much into a single function! Reading and trimming a line is plenty. Adding to that parsing an int and float is probably too much. You should be able to easily move that call to parse almost anywhere else.