# Variables and Constants

## Variables and Mutability

We already covered the basics of variables and mutability in [Guessing Game](../guessing-game), but here's a quick review:

By default, variables are immutable.

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

However, they can be made mutable.

```rust
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.

```rust
const MAX_POINTS: u32 = 100_000;
```

Here's an example of how to do this:

```rust
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!

```rust
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:

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

We can do this:

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

But we can also do this!

```rust
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](https://doc.rust-lang.org/book/second-edition/ch03-01-variables-and-mutability.html#shadowing) 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:

```rust
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.
