Two unused mutable references are seemingly okay

#1

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.

#2

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

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=febc4bc3bbbf7e48a7ccef13cf7fae15
vs
https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=febc4bc3bbbf7e48a7ccef13cf7fae15

2 Likes
#3

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?

4 Likes
#4

That clears it up. Thanks!

1 Like