尽管仔细阅读了文档,但我还是对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中是正确的.
到目前为止,我的理解是,在Road引用前面插入*
,但是,*
是隐式插入的,因此不需要添加它(而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
}
似乎隐式撤销(LaC++)对于不可变引用是正确的,但对于可变引用似乎是正确的.这是为什么?