HiveBrain v1.2.0
Get Started
← Back to all entries
gotcharustCritical

What is the difference between immutable and const variables in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
variablesconstandbetweenthedifferenceimmutablerustwhat

Problem

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 the same? If not, how do they differ?

Solution

const, in Rust, is short for constant and is related to compile-time evaluation. It shows up:

  • when declaring constants: const FOO: usize = 3;



  • when declaring compile-time evaluable functions: 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 reference



Most 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.

Context

Stack Overflow Q#37877381, score: 107

Revisions (0)

No revisions yet.