Search code examples
rustreferencecoerciontype-coercionrust-pin

How get an immutable Pin from a mutable Pin?


How to apply deref coercion from &mut to & for references that are wrapped inside Pin<>? That is, how to borrow Pin<&mut _> as Pin<&_>?

use std::pin::{Pin, pin};

fn take_immutable(_: Pin<&u32>) {}

let mutable_ref = pin!(0u32);
    
// Error: expected struct `Pin<&_>` 
//           found struct `Pin<&mut _>`
take_immutable(mutable_ref);

Solution

  • Pin::as_ref() is your friend:

    take_immutable(mutable_ref.as_ref());