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?
相关问题
- Share Arc between closures
- Function references: expected bound lifetime param
- Pattern matching on slices
- Creating Immutable Classes with Multiple Construct
- How can I iteratively call Sha256::digest, passing
相关文章
- Understanding immutable composite types with field
- How can I convert a f64 to f32 and get the closest
- What is a good way of cleaning up after a unit tes
- How can I unpack (destructure) elements from a vec
- How to import macros in Rust?
- How do I modify a record in erlang?
- How to get struct field names in Rust? [duplicate]
- Confusion between [T] and &[T]
const
is for compile-time constants with everything that entails. For example, you can create a fixed-sized array whose size is aconst
, but you can't do that with alet
binding. Of course, this also means that you can put far, far more things into alet
binding than into aconst
.Constants can not be redefined:
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 containsCell
members, for example) in some cases.Additionally, we can't make global items using let, but it's possible by using const. Here is an example.
for more information about the usages of const, static, and let:
const
andstatic
The story is a little bit longer.
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
andconst
with raw pointers (*mut T
and*const T
) which is not discussed here.