Using a pin more than once

Consider the following code which compiles very happily:

fn f<T>(x: &mut T) {
}

fn g<T>(x: &mut T) {
	f(x);
	f(x);
}

Now consider the following code, which doesn’t:

fn f<T>(x: Pin<&mut T>) {
}

fn g<T>(x: Pin<&mut T>) {
	f(x);
	f(x);
}

I understand why the second example doesn’t compile, at the type system/borrow check level: x has been moved (since it’s not Copy) into the first f(x), and it hasn’t moved out again, so it’s not there any more for the second call.

I understand why Pin<&mut T> isn’t Copy. If it were, you could create two Pin<&mut T>s pointing at the same object, which would violate the “only one mutable reference to an object” rule.

What I don’t understand is what to do about it. Obviously the first example is safe and useful. The second example is useful and should be safe too. Yet it doesn’t work.

What am I missing? How is one supposed to write the first example, but with Pin?

Just do f(x.as_mut())

1 Like

facepalm. Thanks.

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.