4 ms·
> Also, the whole 'move' terminology sounded to me like Rust would move memory around That's exactly what happens: a Rust "move" is under the covers a memcpy()
by cesarb 6y ago
> Also, the whole 'move' terminology sounded to me like Rust would move memory around
That's exactly what happens: a Rust "move" is under the covers a memcpy().
> but it usually referred to the move of ownership.
That's also what happens. For instance, when you move a Vec, you are moving (through memcpy) only three words of memory (a pointer, the length, and the capacity), but you are also "moving" the ownership of the memory behind that pointer. That is, the new Vec is responsible for managing that memory, and the old Vec can no longer be used.
> Also 'consume' didn't make no sense to me. "into_iter consumes a vector" what does it mean?
It means that it takes ownership of the vector, and doesn't give it back.
> Where does the vector go?
It's destroyed within that function. In the case of into_iter() of a vector, it's broken into its component parts (the pointer, the length, and the capacity), and the struct into_iter() returns (which is not a Vec, but something else) is now responsible for managing the memory behind the pointer, and releasing that memory once it's no longer needed.
- Asraelite 6y ago> That's exactly what happens: a Rust "move" is under the covers a memcpy(). Is it really? I had always assumed that the compiler would almost always optimize a move down to nothing, simply reusing the address. If access to the address is still exclusive, what would be the benefit of moving it in memory? memcpy sounds like what would happen in the case of a copy or clone, not a move.
- cesarb 6y agoYes, the optimizer (LLVM) can often optimize memcpy(), and this is not exclusive to Rust: the same optimizations happen with C and C++ (a well-known trick to avoid some undefined behaviors in C is to do a memcpy(), which the optimizer will then elide). It doesn't change that, before the optimization passes, it's doing the equivalent of a memcpy(). > memcpy sounds like what would happen in the case of a copy or clone, not a move. In Rust, copy and move are nearly identical; the only difference is that, after a move, the compiler doesn't let you access the old value. Clone is different, since it can be overridden to do anything the programmer desires, but by default, it's identical to copy.
- MetaDark 6y ago> That's exactly what happens: a Rust "move" is under the covers a memcpy(). Not exactly. The Rust compiler is usually pretty smart about optimizing out memcpy for most moves. For example when returning a large struct from a function, the optimizer could add an "out" reference parameter to the function and the function would directly initialize the return value into that reference.