Let's dig in!
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {}", guess);
}
The first line use std::io
brings the standard io (input/output) library into scope. We've covered main
and println!
, so let's go into let
, mut
, and String::new
. let
is used to defined variables, like so:
let foo = bar;
A standard variable is immutable (cannot be changed), but mut
makes it mutable.
let foo = bar; // immutable
let mut foo2 = bar; // mutable
Here's the error message you will see if you try to change an immutable variable.

Rust also binds variables to a certain type when they are initialized. For example, with line :
let mut guess = String::new();
guess
is bound to an empty string. Here's an example of how this works:

The next part of the code, .read_line(&mut guess)
, calls the read_line
method on the standard input handle to get input from the user. We’re also passing one argument to read_line
: &mut guess
. read_line
requires a string as a parameter and that string must be mutable. The &
indicates that it is a reference. References are immutable by default, so the &mut guess
is required.
Last updated