What is the difference between immutable and const

2020-02-08 05:16发布

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?

5条回答
手持菜刀,她持情操
2楼-- · 2020-02-08 05:33

const is for compile-time constants with everything that entails. For example, you can create a fixed-sized array whose size is a const, but you can't do that with a let binding. Of course, this also means that you can put far, far more things into a let binding than into a const.

查看更多
对你真心纯属浪费
3楼-- · 2020-02-08 05:42

Constants can not be redefined:

let x = 10u32;
const Y:u32 = 20u32;

let x = 11u32;
//error: duplicate definition of value `Y` [E0428]
//const Y:u32 = 21u32;

println!("x={} Y={}",x,Y); //x=11 Y=20
查看更多
Rolldiameter
4楼-- · 2020-02-08 05:48

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 contains Cell members, for example) in some cases.

查看更多
叛逆
5楼-- · 2020-02-08 05:49

Additionally, we can't make global items using let, but it's possible by using const. Here is an example.

const LENGTH:usize = 4;

fn main() {
    let arr:[i32; LENGTH] = [10,20,30,40];

    for i in 0..LENGTH{
        println!("{}", arr[i])
    }
}

for more information about the usages of const, static, and let: const and static

The story is a little bit longer.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-02-08 05:50

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

  • when declaring constants: const FOO: usize = 3;
  • when declaring compile-time evaluable functions: 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 reference

Most 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 and const with raw pointers (*mut T and *const T) which is not discussed here.

查看更多
登录 后发表回答