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.
However, they can be made mutable.
Constants
Constants are immutable (cannot use mut
), they must be type-annotated, and they must be set to a constant expression, not a function.
Here's an example of how to do this:
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!
Shadowing
This is where Rust gets a little weird and acts differently than you might expect. So while we can't do this:
We can do this:
But we can also do this!
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:
If we used mut
instead, it would result in a compile-time error because these are two different types.
Last updated