Rust: let vs const
Nicky Meuleman
Posted on September 24, 2020
To declare a variable in Rust, use the let
keyword.
let num = 5;
By default, variables are immutable, you can't change them.
If you wish to mutate it, you have to explicitly state that by adding mut
to that declaration.
let mut num = 5;
Now, the number stored in the variable named num
may now be changed.
num = 6;
Another piece of data that's immutable, (so can't change) is a constant.
Declared with the const
keyword.
You might already be familiar with this concept, and wonder:
If variables are immutable by default, what's the difference between variables and constants?
— you (maybe)
You aren't allowed to use
mut
on constants. No mutating, ever.The type of a constant must be declared, whereas the type of a variable may be declared.
Constants can only be set to a constant expression, not to the result of a function call or anything that could only be determined at runtime.
As a result, constants are always fixed in size, and known at compile time.
Another, less obvious result, is that constants may not be of a type that requires allocation on the heap, since they're not known at compile time.
- The naming convention for
const
isSCREAMING_SNAKE_CASE
. - The naming convention for
let
issnake_case
.
const SPEED_OF_LIGHT: u32 = 299792458;
Constants can be declared in any scope, including the global scope.
They are valid for the entire runtime of the program inside that scope.
Translation: You can put constants outside of the main
function and it will work.
Posted on September 24, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.