Two unused mutable references are seemingly okay

The Rust docs say “you can only have one mutable reference to a particular piece of data in a particular scope.” The 4-line code example shows the creation of a string, the creation of the first mutable reference, the creation of a second mutable reference, and lastly, a println printing both references.

The bizarre thing is removing the println results in a program that compiles. Initially I thought this was due to dead code elimination by the compiler, but I’m not sure.

The latest version of Rust (2018 edition) is much smarter about this, and takes into account how references are used.



The deal is that, as of Rust 1.31, the compiler sees the scope of the variables a bit differently. In other words, it's not about the scope of the variable itself, but it's the scope of where the variable was actually used.

Does that make sense?


That clears it up. Thanks!

1 Like