You can move !Unpin

submited by
Style Pass
2024-12-04 07:00:03

Although I am now mostly comfortable with Rust, some concepts still elude me. One of them is the exact meaning of Unpin. The documentation says:

I am definitely not the first one to get confused by Unpin. The thing is that, if you’re here, you are probably thinking of Unpin wrong. Unpin is actually a trait for very niche use cases, which you probably don’t need. And, to understand why, you first need to understand Pin and pinning.

Some objects contain references to part of themselves. Common examples are pointing to a slice of a buffer, or linked lists. However, in practice, the most common case in Rust is futures, from asynchronous code.

When you write f(), it calls the asynchronous function. More specifically, it creates an impl Future object, its role is to store the data that needs to be kept while the function is not running. That is, across await points. The lifetime of the future will look like this:

Self-referential objects must not be moved in memory. If you were to do so, it would change their address, and invalidate the references that point to them1.

Leave a Comment