4 ms·
How does Rust resolve move semantics for ~-values at compile time? What does this do: let a: ~Point = ~Point { x: 10, y: 20 }; let b: ~Point = ~Point { x:
by bcoates 14y ago
How does Rust resolve move semantics for ~-values at compile time? What does this do:
let a: ~Point = ~Point { x: 10, y: 20 };
let b: ~Point = ~Point { x: 20, y: 40 };
if (foo()) {
b = a;
}
println(a.x.to_str());
- pcwalton 14y agoIt's a conservative analysis, so your program would be in error as a possible attempt to use a moved value.
- bcoates 14y agoOuch. Can it handle things like conditionally swapping two values or does any conditional assignment break both values? Is there an escape hatch?
- pcwalton 14y agoThere is a swap operator built into the language, so that specific example would work (I think; I haven't checked the code). The escape hatch is to use the generic "Cell<T>" type in the standard library, which gives you dynamic behavior much like C++11 move semantics. The nice thing about the static analysis, though, is that the checks don't have to be performed at runtime if the compiler can prove that the value is always moved at the end of the block.
- lifthrasiir 14y agoYour example does not quite compile (you need to declare `a` and `b` as mutable, `println` is actually `io::println`, `fn main() { ... }` is missing etc.), but given similar code: fn main() { let mut a = ~1; let mut b = ~2; if false { b = a; } io::println(fmt!("%d", *a)); } ...the compiler will assume that `a` can be moved to `b` (although the precise analysis will reveal it can't) and therefore further use of `a` is unsafe. If you really want to assign `a` to `b`, you can do `b = copy a;` (warning: the syntax may change) to explicitly copy it without moving.
- fzzzy 14y agob = a moves a to b, so it would be an error to use a after that point.
- gnuvince 14y agoCompiler error; since a might no longer be defined, it's an error to access it here.
- deleted 14y ago[deleted]