---
# System prepended metadata

title: Pin

---

# Pin

When do you need the function to take `Pin<_>` as the argument? If any of the following is true:
* The function expects the object pinned (i.e. the object should have a fixed address), this is a sign of starting relying on pin safety guarantee.
* The function is a mutable one (i.e. it would take a `&mut self`) and may be called after the object is pinned. Reason: otherwise users may need to use `unsafe` to call these function.
  * What about the function may be called before pinned? A duplicate `&mut self` version or rely on `pin-init` so all mutable functions take `Pin<&mut Self>` ???

`UNPIN` functions:

The Pin safety guarantee (once pinned, always pinned) may be too restrict sometimes, and 
* Put an `# Unpin` comments on the functions that make the object movable again (e.g. removing the object from a global list), notes these functions themselves have to be a `Pin<_>` function. For example,

```rust=
struct A {
    ...
    _pin: PhantomPinned,
}

impl A {
    /// Puts on a list for execution.
    pub fn queue(self: Pin<&mut Self>)
    /// # Unpin
    ///
    /// Removes the object from the global list when return,
    /// can be moved after this.
    pub fn wait_for_finish(self: Pin<&mut Self>)
}
```

Then if these `# Unpin` functions are used to make the objects movable. Add a `UNSOUND: UNPIN:` comment as the move point, e.g.

```rust=

let a = A::new(..);

// UNSOUND: SAFETY: `a` may be moved afterwards, but that's after
// a Unpin function.
let pin = unsafe { Pin::new_unchecked(&mut a)};

pin.as_mut().queue();

// UNSOUND: UNPIN: `wait_for_finish()` makes `a` movable again.
pin.wait_for_finish();

// UNSOUND: Moves `a`.
let b = Box::new(a);

```