Why does intrusive linked list need Pin?

I read about pin's doc here. It says that we need pin for an intrusive linked list. This blog also discussed about the implementation of intrusive linked list using Pin. But why do we actually need pin here? If I want to move an element, I can just update the previous and next element's data fields, which contain pointers to this changed element. This is just like the behaviour of a normal non-intrusive linked list. On the other hand, if we need pin here, then we also need pin for normal non-intrusive linked lists because moving an element invalidates the pointers to it, too.
I think it's a concept misunderstanding for me. I just don't know which part did I totally misunderstand.

Neither of those sources actually say that Pin is required, only that it helps. Pin is really only useful when you need to communicate non-moving guarantees between two different areas of responsibility-- If you control everything, you can uphold the same invariants just fine without ever mentioning Pin if you really want to.


Rust generally assumes that every object is relocatable and so common operations like variable assignment, argument passing, and returning values from functions all implicitly move things. Pin makes it unsafe to do these operations, moving the responsibility of proving that an object hasn't moved from the intrusive linked-list implementation, which can't do anything about it, to the owner of each element in the list, which can.

If those are both you, then Pin is not strictly necessary. On the other hand, if you're writing an intrusive linked-list library intended for someone else to use within their own structs, you'll want to use Pin to indicate that you're relying on the elements not being moved out from under you.

4 Likes

Rust has no move constructors so there's no way to cause code to run every time the user moves their local variable that's part of a list. This means that there's no way to provide a safe API to anything stored on the stack that can become part of a linked list.

Pinning solves this by letting the user promise not to move their stack variable.

5 Likes

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.