Skip to content

Latest commit

 

History

History
58 lines (40 loc) · 1.45 KB

README.md

File metadata and controls

58 lines (40 loc) · 1.45 KB

Reading user input ⌨️

To read user input from the command line, we will use the standard io module

use std::io;

Now, we need a variable to store the user input.

let mut input = String::new();

And we need to print something to ask the user for input.

println!("Please enter your name: ");

Finally, we need to read the user input with the stdin().read_line() method.

io::stdin().read_line(&mut input);
// we give the read_line function a mutable reference to our input variable

The read_line function returns a Result type, which is a type that can either be Ok or Err.

So, we will put this in a match expression.

match io::stdin().read_line(&mut input) {
    Ok(_) => println!("Hello {}", input),
    Err(error) => println!("Error: {}", error),
}

We put a _ in the Ok branch because we don't care about the value of the Result (which is the numeber of bytes that were written to the buffer).

Now, we can run the program.

> cargo run
Please enter your name:
> John
Hello John

Course created by SkwalExe and inspired by Dcode