Error not able to debug

Here I am sending my code it is giving error on Ok(temp) line
Unable to understand this error. Please help somebody

use std::io;

fn main() {

    let mut players: Vec<u8> = Vec::new();

    let mut input = String::new();

    println!("How many players want to play?");

    io::stdin().read_line(&mut input).expect("Error");

    match input.trim().parse() {

        Ok(temp) =>{

                println!("Correct {:?} players want to play",input );

            },

        Err(_)=>println!("Only numbers allowed");

    }

}

The error says method call: parse::<F>
8 | Ok(temp)=>{
| ^^^^ cannot infer type

You forgot to tell it what to parse to

match input.trim().parse::<i32>()

Full sample
Note: I'm not really sure why you were using the input to print instead of the temp so just printed that instead.

use std::io;

fn main() {
    let mut players: Vec<u8> = Vec::new();

    let mut input = String::new();

    println!("How many players want to play?");

    io::stdin().read_line(&mut input).expect("Error");

    match input.trim().parse::<i32>() {
        Ok(temp) => {
            println!("Correct {} players want to play", temp);
        }

        Err(_) => println!("Only numbers allowed"),
    }
}

1 Like

If you look at the method signature for parse in the documentation, it’s fn parse<F>(&self)->Result<F, ...>. That <F> means that it is capable of returning several different types. The particular one you get will be determined by context, such as the type of variable you are storing the result into.

The error you’re getting, “cannot infer type,” means that you’re not doing anything with the result that would tell the compiler what type it needs to be. You can fix this by specifying the type explicitly, like @zireael9797 showed, or you can do something with the result, like this:


    match input.trim().parse() {
        Ok(num_players) => {
            println!("Correct {:?} players want to play", input);
            players.resize(num_players, 0);
        }

        Err(_) => {
            println!("Only numbers allowed");
        }
    }

What exactly is going on in this case? the type for parse is being inferred based on what vec.resize() wants?

Yes, exactly. It’s the same mechanism that would let you write something like

let x:u32 = input.parse().unwrap();

The compiler knows that:

  • parse() produces a Result<F, ...>,
  • unwrap() turns a Result<F, ...> into an F, and
  • The output of unwrap is used somewhere that must be a u32.

Therefore, F = u32 and there are no more generic types left to figure out.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.