此代码:
let mut a2 = 99;
let b: *mut i32 = &mut a2;
*b = 11; // does not compile , even after unsafe {*b}
生成错误:
error[E0133]: dereference of raw pointer requires unsafe function or block
--> src/main.rs:4:5
|
4 | *b = 11;
| ^^^^^^^ dereference of raw pointer
但是这段代码有效:
let mut a2 = 99
let b = &mut a2;
*b = 11;
两者有什么区别?
答案 0 :(得分:6)
两者有什么区别?
一个是原始指针(*mut _
),另一个是引用(&mut _
)。正如书中所说:
编译器保证引用永远不会悬空
此外,引用永远不会是NULL
。取消引用引用始终是安全的。由于编译器无法保证其中任何一个,因此取消引用原始指针并不总是安全的。因此,您需要一个unsafe
块:
unsafe { *b = 11; }
另见: