Pin and Unpin
Today I was watching
Bay Area Rust Meetup. Adam
Chalmers does a great job describing what's Pin
and Unpin
in Rust.
Pin
is basically a way to tell Rust compiler that we don't want to move
particular struct. What does it mean? Most of the time, we need to think about
Pin
in cases when our struct contains reference to itself, for example we have a
field data
and a separate field point
pointing to the field data
.
Now, what will happen when we move the structure in the memory? Obviously data
field will move as well. What about point
field? It will still be pointing to
the old place in the memory and this becomes an issue because now we have a
pointer pointing to invalid region in the memory.
Rust's solution to that is a struct Pin
which basically tells the compiler that
we can't move Pin
ed struct. When we try this, then we'll get a compiler
error. Unless the struct we are Pin
ning implements marker trait Unpin
, then
the compiler knows that Pin
ning doesn't have an influence, and we can move the
struct around.
The above is rough and definitely not complete description of Pin
and Unpin
.
More detailed explanation can be found
here.