std-method

Pin::set: replace by destroying the old value in place

The pinning guarantee allows a pinned value to be destroyed at its location before replacing it with another valid value. Pin::set does this without returning the old value. This differs from mem::replace, which moves the previous value out. Expected stdout (not executed): 1 2 2 Common mistake: Assuming a pinned value can never be replaced, or trying to extract the old one.

Formal Syntax & Structure

rust syntaxrust
p.set(value: T) where T: Sized

Working Example

Example Snippetrust
fn main() {    use std::{marker::PhantomPinned, cell::Cell, rc::Rc};    struct Item { id: u32, drops: Rc<Cell<u32>>, _pin: PhantomPinned }    impl Drop for Item { fn drop(&mut self) { self.drops.set(self.drops.get() + 1); } }    let drops = Rc::new(Cell::new(0));    let mut p = Box::pin(Item { id: 1, drops: drops.clone(), _pin: PhantomPinned });    p.set(Item { id: 2, drops: drops.clone(), _pin: PhantomPinned });    println!("{} {}", drops.get(), p.id);    drop(p);    println!("{}", drops.get());}
Rust Reference