我正在阅读 "Rust Book" 网站,以便学习这门语言,为即将到来的工作面试做准备。在关于向量的章节中,有两个代码示例:
fn main() {
let v = vec![100, 32, 57];
for i in &v {
println!("{}", i);
}
}
并且:
fn main() {
let mut v = vec![100, 32, 57];
for i in &mut v {
*i += 50;
}
}
现在我想知道,为什么在第一个示例中,当我们将向量元素 i 的引用传递给:
println!("{}", i);
但是在将 50 添加到向量的每个元素的示例中,我们需要在加上 50 之前解引用元素吗?
为什么不能这样做:
fn main() {
let v = vec![100, 32, 57];
for i in &v {
println!("{}", *i); // why don't we have to dereference before we pass to println!?
}
}
或者:
fn main() {
let mut v = vec![100, 32, 57];
for i in &mut v {
i += 50; // why can't we just add directly to the reference like this?
}
}
我可能误解了我所读的内容,但我认为Rust能自动识别何时需要解引用,何时不需要。我猜我不理解为什么我们需要在这两个示例中解引用(或不解引用)。 我提供的两个示例都有我想知道的特定代码注释。
println!
自动引用任何你尝试格式化的值的事实。如果你想打印一个地址,你必须将其引用转换为原始指针。 - rodrigo