【发布时间】:2016-07-20 00:30:52
【问题描述】:
尽管仔细阅读了文档,但我对 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
}
似乎隐式取消引用(a la C++)对于不可变引用是正确的,但对于可变引用则不然。这是为什么呢?
【问题讨论】:
标签: reference rust dereference ampersand