3 ms·
This is all part of "destructuring pattern matching". Let's say we have: struct Something<T>(T); let x = 42; When we say: let y = Something(&x);
by thristian 9y ago
This is all part of "destructuring pattern matching". Let's say we have:
struct Something<T>(T);
let x = 42;
When we say:
let y = Something(&x);
...we're constructing a value of a particular type on the right-hand-side of the `=`. Written out, it would be something like "take the value x, calculate its address in memory, and wrap that reference in Something()".
let Something(&z) = y;
...does the reverse operation. Written out, it would be something like "take the value y, remove the Something() wrapper to get the value inside, dereference the pointer to find the value pointed to, then assign a copy of that value to the variable z". At the end, z == x.
Note that the last step is copying a value: it only works if value is of a type that can be safely memcpy()'d (in Rust terminology, if the type implements the Copy trait). In this case, the value happens to be the integer 42, and integers are Copy, so it all works out. However, not all types are Copy, so if you can't copy the value, what happens?
If the value you're destructuring owns the inner value, it's easy—you just become the new owner:
let x = Something(123); // x owns this Something instance.
let y = Something(x); // the value from x is moved into y.
let Something(z) = y; // the value inside y is moved into z.
On the other hand, if the value you're destructuring doesn't own the inner value, you can't just take ownership of it. If you want a handy name to use when talking about that value, it's going to need to be a pointer.
let x = Something(42); // a value that is not Copy.
let y = Something(&x); // a reference, so we can't take ownership
//let Something(&z) = y; // Can't take ownership of x!
let Something(ref z) = y; // z is a reference to x
You can play with these examples in the Rust Playground: https://is.gd/LhrphO https://is.gd/LhrphO
- Veedrac 9y agolet x = Something(42); // a value that is not Copy. let y = Something(&x); // a reference, so we can't take ownership let Something(ref z) = y; // z is a reference to x z is a reference to &x, and is thus of type &&i32. You should normally just do let Something(z) = y;