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 th
A const
does not represent a memory location but a value. const
values are directly inlined at usage location. Any temporary objects that are created during expression evaluation are accessible only by the compiler during compile time. Can be scoped globally. Can not reference runtime items. Must be type annotated.
Let values represent a memory location. Immutability for let
binding is a compiler enforced thing can be changed with mut
modifier. It is runtime construct. Always locally scopped. Their types can be inferred by the compiler.
For completeness, a static
also represents a memory location like let but any references to the same static are actually a reference to the same memory location. Static are, well, statics. They are compiled into executable and accessible for the entire lifetime of the running program. Can be scoped globally. Can reference other statics. Must be type annotated.