Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust - read input from STDIN

  • std::io

  • String

  • stdin

  • read_line

  • expect

  • Module std::io

  • String::new() - Creates a new mutable empty string

  • &mut name passes a reference of the variable to the function as mutable variable. & indicates it is a reference.

  • read_line reads a line from the command line

use std::io;

fn main() {
    let mut name = String::new();

    println!("Please type in your name:");
    io::stdin()
        .read_line(&mut name)
        .expect("Failed to get input");

    println!("Hello {}, how are you?", name);
}
Please type in your name:
Foo Bar
Hello Foo Bar
, how are you?

Two problems:

  • The response looks broken. It has a newline after the name.
  • After the prompt the program waits on a new line.