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

前端 未结 6 2105
广开言路
广开言路 2020-12-13 17:12

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

6条回答
  •  北海茫月
    2020-12-13 17:39

    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.

提交回复
热议问题