Metadata
-
Date
-
Tagged
-
Older post
-
Newer post
Rust: let vs const
To declare a variable in Rust, use the let
keyword.
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.
Now, the number stored in the variable named num
may now be changed.
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 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
.
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.