# Variables and Constants

## Variables and Mutability

We already covered the basics of variables and mutability in [Guessing Game](/rust/guessing-game.md), 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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jmkoni.gitbook.io/rust/common-concepts/variables-and-constants.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
