I learned that if a variable is not explicitly declared mutable using mut
, it becomes immutable (it cannot be changed after declaration). Then why do we have the const
keyword in Rust? Aren't they same? If not, how do they differ?
Immutable makes the contract that this object will not change, whatsoever (e.g. Python tuples, Java strings). Const makes the contract that in the scope of this variable it will not be modified (no promise whatsoever about what other threads might do to the object pointed to during this period, e.g. the C/C++ keyword).
In Rust, variables are immutable by default, which means that their values cannot be changed. If a new value is assigned to a variable that was declared with the let keyword, the program won't compile: 4.
By default, variables are immutable − read only in Rust. In other words, the variable's value cannot be changed once a value is bound to a variable name. Let us understand this with an example. The error message indicates the cause of the error – you cannot assign values twice to immutable variable fees.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned.
const
, in Rust, is short for constant and is related to compile-time evaluation. It shows up:
const FOO: usize = 3;
const fn foo() -> &'static str
These kinds of values can be used as generic parameters: [u8; FOO]
. For now this is limited to array size, but there is talk, plans, and hope to extend it further in the future.
By contrast, a let
binding is about a run-time computed value.
Note that despite mut
being used because the concept of mutability is well-known, Rust actually lies here. &T
and &mut T
are about aliasing, not mutability:
&T
: shared reference&mut T
: unique referenceMost notably, some types feature interior mutability and can be mutated via &T
(shared references): Cell
, RefCell
, Mutex
, etc.
Note: there is an alternative use of mut
and const
with raw pointers (*mut T
and *const T
) which is not discussed here.
const
is not for variables; it's for constant values which may not be stored anywhere; they're effectively an alias for a literal value.
Non-mut
let
declares an actual variable which is created at runtime, can be moved (and no longer accessible), and even have interior mutability (if it contains Cell
members, for example) in some cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With