`Pin>` vs `Rc>`

⚓ rust    📅 2025-06-12    👤 surdeus    👁️ 2      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: `Pin>` vs `Rc>`

Context: I've got a data structure (call it Thing) which is always passed around in an Rc, and Thing currently has an id field, because two Things with the same data are not necessarily the same thing (and may become different in the future because of interior mutability). So my implementation of PartialEq for Thing compares their ids; Hash also just uses the id. Generating and storing ids seems unnecessary though, seeing as the Rc provides an id for us in the form of its backing pointer. I was however a bit hesitant to use Rc::as_ptr/ptr_eq for these purposes though, because I wasn't certain that the pointer would never change. Posts in Does comment on Rc<T>.as_ptr() imply Rc<T> is always pinned? suggest that it'd be totally fine so long as I don't use make_mut; I don't use use make_mut, but I'd like to make certain that I don't shoot myself in the foot later on.

The actual question: If I want to guarantee that the pointer I obtain from an Rc will always point to the same data for the lifetime of that Rc, should I be using Pin<Rc<Thing>> or Rc<Pin<Thing>>?

To me, the former implies that the address of the Rc won't change, which isn't helpful because I'll be cloning Rcs anyway, whilst the latter implies that the location of the Thing, which will be the backing pointer of the Rc, won't change. Moreover, it seems to me that doing anything useful with a Pin<Rc<T>> is quite difficult because I don't think you can just access a &Rc<T> from a Pin<Rc<T>>, which you need for doing anything useful with an Rc. However, I do suspect that I don't understand Pin very well, having only read its documentation for the first time today.

Thanks in advance for any clarity you can shed on the matter.

1 post - 1 participant

Read full topic

🏷️ rust_feed