Rust 中的不可变变量和 const 变量有什么区别? [英] What is the difference between immutable and const variables in Rust?

查看:24
本文介绍了Rust 中的不可变变量和 const 变量有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到,如果一个变量没有使用 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的缩写,与compile-time有关评价.它出现了:

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

  • 声明常量时:const FOO: usize = 3;
  • 在声明编译时可评估函数时:const fn foo() ->&'静态字符串

这些类型的值可以用作泛型参数:[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(共享引用)进行变异:CellRefCellMutex

Most notably, some types feature interior mutability and can be mutated via &T (shared references): Cell, RefCell, Mutex, etc.

注意:mutconst 有原始指针(*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 变量有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆