问题描述
我了解到,如果未使用 mut
显式声明变量是可变的,则该变量将变为不可变的(声明后无法更改)。那为什么在Rust中有 const
关键字呢?他们不一样吗?如果没有,它们有何不同?
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?
推荐答案
const
,在Rust中,是 constant 的缩写,与编译时评估有关。它会显示:
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
- when declaring constants:
const FOO: usize = 3;
- when declaring compile-time evaluable functions:
const fn foo() -> &'static str
这些类型的值可用作通用参数: [u8; FOO]
。目前,这仅限于阵列大小,但是有讨论,计划,并希望在将来进一步扩展。
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.
相比之下, let
绑定是关于运行时的计算值。
By contrast, a let
binding is about a run-time computed value.
请注意,尽管 mut
因为可变性的概念是众所周知的,所以使用Rust实际上就是在这里。 & T
和&mut T
与别名有关,而不是可变性:
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
:共享引用 -
& ; mut T
:唯一引用
&T
: shared reference&mut T
: unique reference
最值得注意的是,某些类型具有内部可变性,并且可以通过& T
(共享引用)进行突变: Cell
, RefCell
, Mutex
等
Most notably, some types feature interior mutability and can be mutated via &T
(shared references): Cell
, RefCell
, Mutex
, etc.
注意:可以将 mut
和 const
与原始指针( * mut T
和 * const T
),此处不再讨论。
Note: there is an alternative use of mut
and const
with raw pointers (*mut T
and *const T
) which is not discussed here.
这篇关于Rust中的不可变变量和const变量有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!