expression

Tie a borrowed handle to its owner

A borrowed wrapper must not outlive the owning object. This model stores a pointer derived from a shared reference and records that borrow in its type. A real foreign wrapper also needs a guarantee that the library will not mutate or invalidate the object during the borrow. Expected stdout (not executed): 31 Common mistake: Giving a borrowed wrapper an unconstrained static lifetime.

Formal Syntax & Structure

rust syntaxrust
PhantomData<&'a T>

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::{marker::PhantomData, ptr::NonNull};    struct View<'a> { ptr: NonNull<u32>, _borrow: PhantomData<&'a u32> }    impl<'a> View<'a> {        fn new(owner: &'a u32) -> Self { Self { ptr: NonNull::from(owner), _borrow: PhantomData } }        fn get(&self) -> u32 {            // SAFETY: the original shared borrow remains valid and is read-only.            unsafe { *self.ptr.as_ptr() }        }    }    let owner = 31_u32;    let view = View::new(&owner);    println!("{}", view.get());}
Rust Reference