Variables and Constants

Variables and Mutability

We already covered the basics of variables and mutability in Guessing Game, but here's a quick review:

By default, variables are immutable.

let x = 5;
x = 6; // this will result in an error

However, they can be made mutable.

let mut x = 5;
x = 6; // this is ok!

Constants

Constants are immutable (cannot use mut), they must be type-annotated, and they must be set to a constant expression, not a function.

const MAX_POINTS: u32 = 100_000;

Here's an example of how to do this:

fn main() {
  let mut points = 0;
  loop {
    println!("{}", points);
    if points >= 100 {
      break;
    }
    points = points + 1;
  }
}

This works. But it's not really clear. Why are we only going up to 100? Any future developer does not know why I'm doing what I'm doing. So let's improve it with a constant!

fn main() {
  const MAX_POINTS: u32 = 100;
  let mut points = 0;
  loop {
    println!("{}", points);
    if points >= MAX_POINTS {
      break;
    }
    points = points + 1;
  }
}

Shadowing

This is where Rust gets a little weird and acts differently than you might expect. So while we can't do this:

let x = 5; // immutable
x = x + 1; // no bueno

We can do this:

let mut x = 5;
x = x + 1;

But we can also do this!

let x = 5; // immutable!
let x = x + 1; // but this works!

let is essentially creating a new value and Rust allows you to have a value with the same name as a previous value. This really becomes handy when you want to essentially change the variable type. The Rust Book has a great example of this:

For example, say our program asks a user to show how many spaces they want between some text by inputting space characters, but we really want to store that input as a number:

let spaces = "      ";
let spaces = spaces.len();

If we used mut instead, it would result in a compile-time error because these are two different types.

Last updated