Get user input as text

Get user input as text

Reading Time: ~ 1 minute

Input as text

use std::io::stdin

println!("What is your name?");

let mut name = String::new();
stdin().read_line(&mut name).expect("Couldn't read the line");

println!("Hi {}!", name);
What is your name?
John
Hi John!

We needed:

  1. to import the standard input module (stdin)
  2. create a mutable variable to serve as the buffer for the reader and hold the user’s answer
  3. At least provide the “expect” call:
    • The expect call reacts to an Ok or an Err from the read_line. If it encounters the Err it will print what is written and exit.

 

Alternative to expect

use std::io::stdin;

println!("What is your name?");

let mut name = String::new();
match io::stdin().read_line(&mut name) {
    Ok(n) => {
        println!("Hi {}!", n);
    }
    Err(error) => println!("error: {}", error),
}
What is your name?
John
Hi John!

 

Leave your opinion, start a discussion, share an experience or just a compliment...

%d bloggers like this: