Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Rust program ignore immutability

Tags:

rust

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);
}
like image 317
Viraj Avatar asked Mar 24 '17 04:03

Viraj


People also ask

Is Rust immutable?

By default, all variables in Rust are immutable.

Why is Rust immutable by default?

There is no single reason that bindings are immutable by default, but we can think about it through one of Rust's primary focuses: safety. If you forget to say mut , the compiler will catch it, and let you know that you have mutated something you may not have intended to mutate.


1 Answers

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
    
like image 148
Alec Avatar answered Oct 28 '22 17:10

Alec