Incomplete mini-guide to self-reference (non-movable objects)


(Based off of )

An object containing a self-reference cannot be moved. But it doesn’t need to literally contain the self reference.

Let’s start with
We make a reference to a part of MyLittleImmovableType and store it in MyLittleImmovableType itself. Observe that since MyLittleImmovableType contains a reference, the lifetime of the reference is part of the type (MyLittleImmovableType<'a>).

Let’s factor out the creation of the self-reference into another function, as seen in Uncommenting std::mem::drop still leads to a compilation error.

But, the type system tries to avoid relying on the contents of functions to determine what is valid or not. So it must be the type of the function tying things together. And indeed, in we can comment out the assignment of the reference, and you are still unable to move the object, as seen when attempting to uncomment std::mem::drop. It’s the mere action of calling the function with the type that coerces the lifetime in this way.

So we can simplify, as in There is no literal reference being stored, nor even room for it. It’s just lifetime manipulation.

As a side note, fn immobilize<'a, 'b: 'a>(_pony: &'b mut MyLittleImmovableType<'a>) { works too (the other way around does not work), so the passed in reference lives as long as the type. I can only assume that in actuality the lifetime has to match.

Stable way to prevent moving out of a type
How to : returning values referencing local Rc?