Mem::replace for a variable that supports moving out?


This example for the num-bigint crate features the statement

f0 = std::mem::replace(&mut f1, f2);

instead of

f0 = f1;
f1 = f2;

From what I can see from reading the documentation and the source of replace both should be equivalent if the variable f1 supports moving out, which it does.

I would like to ask whether I am missing something here - does using replace provide any advantage in the above case?

1 Like

Personally I'd say that replace reads a bit better, but you're correct that it isn't necessary when you have access to the value directly.

1 Like

Yeah, replace communicates the intention clearly. Its real advantage is when all you have is a mutable reference, in which case you couldn't move the original value.


IIRC, the version without replace didn't used to be allowed in earlier versions of the compiler, before the borrow checker got smarter. (Importantly, if you do anything else between the lines that could call a function, then it won't work, because the function might unwind.) I think this became possible when rustc moved from HIR borrowck to MIR borrowck a long time ago (pre 2018, pre NLL).

A lot of us older Rust users (including myself) tend to have learned when to use these functions to express interesting and just instinctively use them to accomplish things like this without realizing it's not necessary here/anymore.

1 Like

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.