Why does this Rust program ignore immutability

浪尽此生 提交于 2019-12-23 08:56:29

问题


I have the following Rust program and I expect it to result in an compilation error since x is reassigned later. But it complies and gives output. Why?

fn main() {
   let (x, y) = (1, 3);
   println!("X is {} and Y is {}", x, y);

   let x: i32 = 565;
   println!("Now X is {}", x);
}

回答1:


Rust actually lets you shadow other variables in a block, so let x: i32 = 565; is defining a new variable x that shadows the x defined earlier with let (x,y) = (1,3);. Note that you could even have redefined x to have a different type since the second x is a whole new variable!

fn main(){
   let x = 1;
   println!("Now X is {}",x);

   let x = "hi";
   println!("Now X is {}",x);
}

This reddit thread goes into more detail about why this is useful. The two things that are mentioned that seem interesting are:

  • For operations which take ownership of the variable, but return another variable of the same type, it sometimes "looks nice" to redefine the returned variable to have the same name. From here:

    let iter = vec.into_iter();
    let iter = modify(iter);
    let iter = double(iter);
    
  • Or to make a variable immutable:

    let mut x;
    // Code where `x` is mutable
    let x = x;
    // Code where `x` is immutable
    


来源:https://stackoverflow.com/questions/42991325/why-does-this-rust-program-ignore-immutability

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!