此代码:
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;这两者有什么区别呢?
发布于 2017-12-18 19:28:22
这两者有什么区别呢?
一个是原始指针(*mut _),另一个是引用(&mut _)。正如书上说的:
编译器保证引用永远不会悬空。
此外,引用永远不会是NULL。取消引用总是安全的。取消引用原始指针并不总是安全的,因为编译器不能保证这两者都是安全的。因此,您需要一个unsafe块:
unsafe { *b = 11; }另请参阅:
https://stackoverflow.com/questions/47874621
复制相似问题