How does Rust provide move semantics?

前端 未结 4 2135
傲寒
傲寒 2020-11-27 16:24

The Rust language website claims move semantics as one of the features of the language. But I can\'t see how move semantics is implemented in Rust.

Rust boxes are th

4条回答
  •  一个人的身影
    2020-11-27 17:13

    Rust supports move semantics with features like these:

    • All types are moveable.

    • Sending a value somewhere is a move, by default, throughout the language. For non-Copy types, like Vec, the following are all moves in Rust: passing an argument by value, returning a value, assignment, pattern-matching by value.

      You don't have std::move in Rust because it's the default. You're really using moves all the time.

    • Rust knows that moved values must not be used. If you have a value x: String and do channel.send(x), sending the value to another thread, the compiler knows that x has been moved. Trying to use it after the move is a compile-time error, "use of moved value". And you can't move a value if anyone has a reference to it (a dangling pointer).

    • Rust knows not to call destructors on moved values. Moving a value transfers ownership, including responsibility for cleanup. Types don't have to be able to represent a special "value was moved" state.

    • Moves are cheap and the performance is predictable. It's basically memcpy. Returning a huge Vec is always fast—you're just copying three words.

    • The Rust standard library uses and supports moves everywhere. I already mentioned channels, which use move semantics to safely transfer ownership of values across threads. Other nice touches: all types support copy-free std::mem::swap() in Rust; the Into and From standard conversion traits are by-value; Vec and other collections have .drain() and .into_iter() methods so you can smash one data structure, move all the values out of it, and use those values to build a new one.

    Rust doesn't have move references, but moves are a powerful and central concept in Rust, providing a lot of the same performance benefits as in C++, and some other benefits as well.

提交回复
热议问题