来自Rust 编程 (PDF)的示例:
#[derive(Debug)]
enum IntOrString {
I(isize),
S(String),
}
fn corrupt_enum() {
let mut s = IntOrString::S(String::new());
match s {
IntOrString::I(_) => (),
IntOrString::S(ref p) => {
s = IntOrString::I(0xdeadbeef);
// Now p is a &String, pointing at memory
// that is an int of our choosing!
}
}
}
corrupt_enum();
编译器不允许这样做:
error[E0506]: cannot assign to `s` because it is borrowed
--> src/main.rs:13:17
|
12 | IntOrString::S(ref p) => {
| ----- borrow of `s` occurs here
13 | s = IntOrString::I(0xdeadbeef);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `s` occurs here
但假设确实如此;怎么回事
现在
p
是&String
, 指向我们选择的 int 内存!
是坏事吗?