[SOLVED] Is there a difference between Pin> and Box>?

Issue

This Content is from Stack Overflow. Question asked by laptou

In Rust, are there any functional differences between Pin<Box<T>> and Box<Pin<T>>? I think that they should behave the same, but I’m not sure.



Solution

Pin<Box<T>> is what you want. Box<Pin<T>> will not work at all.

Pin requires its type to be a pointer of some kind. It then prevents you from moving out of this pointer (if the pointee isn’t Unpin), by requiring unsafe to access it mutably. In Pin<Box<T>> Box<T> is the pointer. It is common because you can create it safely (as opposed to Pin<&mut T> that without macros can only be created unsafely) because you give the ownership of the Box to it, and thus you cannot access the inner T not through the Pin. Box<Pin<T>>, on the other hand, is useless: it is impossible to create if T does not implement Deref (as Pin‘s constructors require that, because they are meant to use with pointers) and even if T does, the Box is redundant: you already have a pointer, there is no need to wrap it in Box. In addition, you cannot create an instance of Box<Pin<T>> if the <T as Deref>::Target does not implement Unpin without unsafe code, and there is little benefit in Pin with Unpin types (it can be passed to APIs that require it, such as Future::poll(), but in that case you don’t need the Box).


This Question was asked in StackOverflow by laptou and Answered by Chayim Friedman It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?