尽管已经彻底阅读了文档,但我对Rust中的&
和*
符号的含义以及Rust参考究竟是什么还感到困惑。
在这个例子中,它似乎类似于C++引用(也就是在使用时自动取消引用的地址):
fn main() {
let c: i32 = 5;
let rc = &c;
let next = rc + 1;
println!("{}", next); // 6
}
然而,以下代码的功能完全相同:
fn main() {
let c: i32 = 5;
let rc = &c;
let next = *rc + 1;
println!("{}", next); // 6
}
在C++中,使用*
来取消引用并不正确。因此,我想了解为什么在Rust中这样做是正确的。
我的理解是,在Rust中,在引用前加上*
可以取消引用,但*
会自动插入,因此您不需要添加它(而在C++中,它会自动插入,如果您插入它,编译时会出错)。
然而,像下面这样的代码将无法编译:
fn main() {
let mut c: i32 = 5;
let mut next: i32 = 0;
{
let rc = &mut c;
next = rc + 1;
}
println!("{}", next);
}
error[E0369]: binary operation `+` cannot be applied to type `&mut i32`
--> src/main.rs:6:16
|
6 | next = rc + 1;
| ^^^^^^
|
= note: this is a reference to a type that `+` can be applied to; you need to dereference this variable once for this operation to work
= note: an implementation of `std::ops::Add` might be missing for `&mut i32`
但这个有效:
fn main() {
let mut c: i32 = 5;
let mut next: i32 = 0;
{
let rc = &mut c;
next = *rc + 1;
}
println!("{}", next); // 6
}
似乎对于不可变引用,隐式解引用(类似于C ++)是正确的,但对于可变引用则不是。为什么会这样?