Question about `Pin::new()`

A whole brand new world to me, too much to understand.. :smiling_face_with_tear:
I totally understand why rust provide the unpinned Pin by your previously patient and detailed answer.

But with one more question, why designed Pin::new(p: P<T>)(the default constructor semantically) for T: Unpin in particularly but not for T: !Unpin that used more often? (which I mean "counterintuitive")

My guess is that Unpin is the one with intuition in rust because most types impls Unpin and move always considered to be safe according to unpin docs. Is that right?

Trait std::marker::Unpin

pub auto trait Unpin { }

Types that can be safely moved after being pinned.

Rust itself has no notion of immovable types, and considers moves (e.g., through assignment or mem::replace) to always be safe.
...

The constructor for T: !Unpin is the unsafe Pin::new_unchecked method. That method is not used more often, and it is unsafe, which makes quite it inconvenient to use.

For the case of T: !Unpin, the value is usually pinned via some other mechanism:

  • The .await keyword pins it for you behind the scenes.
  • The Box::pin method is safe and works for T: !Unpin.
  • The pin! macro is safe and works for T: !Unpin.
3 Likes

Isn't Pin::new_unchecked designed for T: ?Unpin? :sweat_smile: It's unsafe because of the ambiguity. And I think we do want a pinned value in general (perhaps this is the root of the misunderstanding..)

Well, your question was about T: !Unpin, which is why I talked about it. It's true that it also works for T: Unpin, but it does the same as Pin::new in that case.

It's unsafe because it accepts T: !Unpin types. The fact that you can also pass T: Unpin types to it is not the cause of the unsafety.

Why is that.. :hushed: Can u be more specific?

Because if an Pin<&mut T> exists for a T: !Unpin type, then there are a whole bunch of safety requirements that must be true. Calling the Pin::new_unchecked method on a T: !Unpin type causes a Pin<&mut T> to exist without checking whether those requirements are true. Therefore the method cannot possibly be safe.

1 Like

I see. I feet that it's similar with the only constant is change or absolute motion and relative static. Making unpinned data move will always be safe, because it doesn't change anything. But considering T: !Unpin be pinned need restrictions such as T: !Unpin can only be pinned within Pin<&mut T>'s lifetime.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.