Appearance
Move语义5: exercises/move_semantics/move_semantics5.rs
题目
rust
// move_semantics5.rs
//
// Make me compile only by reordering the lines in `main()`, but without adding,
// changing or removing any of them.
//
// Execute `rustlings hint move_semantics5` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE
fn main() {
let mut x = 100;
let y = &mut x;
let z = &mut x;
*y += 100;
*z += 1000;
assert_eq!(x, 1200);
}
通过对main()
函数中的代码行进行重新排序,不添加、修改、删除任何行,让代码通过编译。
题目解析
这个题目我们需要仔细推理每个可变借用的范围。
首先有变量x,然后创建了两个x的可变借用y和z,后面由通过y和z都对x进行了修改。
这里同一时间存在两个对同一数据的可变借用,可能存在数据竞争问题。
rust
fn main() {
let mut x = 100;
let y = &mut x;
*y += 100;
let z = &mut x;
*z += 1000;
assert_eq!(x, 1200);
}