Function that return multiple types

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”);

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


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");

Oh. So it was simpler than I thought.


But this means that I have to explicitly declare the type of the variable that is going to receive the return value?

let nb1:f64 = read_value().expect(“Error message”);

let nb1:f64 = read_value().unwrap();

Or is there a better way?

You can specify the type for the generic parameter explicitly: let nb1 = read_value::<f64>().unwrap(). It’s not better, just different.

Depending on context, type inference can figure out the type itself from surrounding type requirements in a lot of cases.


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.

This topic is temporarily closed for 4 hours due to a large number of community flags.

This topic was automatically opened after 4 hours.