In Rust, what is !Unpin

Viewed 156

I am unable to locate the documentation for !Unpin referred to here in the docs.

More generally, the ! operator seem to lack corresponding documentation regarding traits. Specifically, it seems to represent Not as in Not Unpin or perhaps Not Unpinable in this case. I suppose it is different from Pin in some way otherwise it would be redundant. Currently, searching for the documentation is challenging since ! occurs so frequently otherwise.

It would be good if the operator behavior of ! on traits could be included in Appendix B: Operators and Symbols of the docs.

1 Answers

Unpin is one of several auto-traits, which are implemented automatically for any type that's compatible with it. And in the case of Unpin, that's, well, basically all of the types.

Auto-traits (and only auto-traits) can have negative implementations written by preceding the trait name with a !.

// By default, A implements Unpin
struct A {}

// But wait! Don't do that! I know something you don't, compiler.
impl !Unpin for A {}

Unpin, specifically, indicates to Rust that it is safe to move values of the implementing type T out of a Pin. Normally, Pin indicates that the thing inside shall not be moved. Unpin is the sort of opposite of that, which says "I know we just pinned this value, but I, as the writer of this type, know it's safe to move it anyway".

Generally, anything in Safe Rust is Unpin. The only time you'd want to mark something as !Unpin is if it's interfacing with something in another language like C. If you have a datatype that you're storing pointers to in C, for instance, then the C code may be written on the assumption that the data never changes addresses. In that case, you'd want to negate the Unpin implementation.

Related