Why do I need rebinding/shadowing when I can have mutable variable binding? Consider:
let x = a();
let x = b(x);
vs.
let mut x = a();
x = b(x);
Mutable variable binding allows a mutable borrow of that variable over this. But does shadowing have some advantages over mutable bindings?
One answer I found myself: shadowing can change variable type.
Because the two have totally different effects.
To really understand what is going on, we need to start at the beginning: what is a binding? What does binding mean?
Let's consider a simple function:
fn hello() -> String;
.When invoking this function like so:
What happens?
The function returns a
String
, which is promptly discarded (executingDrop
as it is thereby freeing its memory).The result is dropped because it was not bound to a variable name, and the rules of the language say that if not bound then it can be promptly dropped1.
If we bind this result, however, we prolong the life of this value, and we can access it via this binding... for a while.
This is the issue at hand: in Rust, the lifetime of a value is independent from the scope of a binding.
A value need not even be dropped before its binding exits its scope: it can be transferred to another (similar to returning from a function).
1 the same happens if binding to
_
.So, now we armed with the fact that bindings and values differ, let's examine the two snippets.
A first shadowing snippet, differing from yours:
Steps, in order:
a()
creates a value, which is bound tox
b()
creates a value, which is bound tox
b()
is droppeda()
is droppedNote that the fact that
x
is re-bound does not affect the lifetime of the value that was previously bound.Technically, it behaves exactly as if the result of
b()
was bound toy
, with the sole exception that the previousx
binding is not accessible whiley
is in scope.Now, the mutable snippet:
Steps, in order:
a()
creates a value, which is bound tox
b()
creates a value, which is bound tox
, and the previous value (created bya()
) is droppedb()
is droppedOnce again, accessing the previous value is impossible, however whilst with shadowing it's impossible temporarily (if shadowing in a smaller scope), with assignment it's impossible forever since the value is dropped.