我正在浏览"铁 rust 书"网站,为即将到来的求职面试学习语言.在向量一章中,有两个代码示例:
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;
}
}
现在我想知道,为什么对于第一个样本,当我们把对向量元素100的引用传递到:
println!("{}", i);
但在我们给向量的每个元素加50的例子中,我们必须先用*go 引用元素,然后再加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?
}
}
I must have misunderstood what I read, but I thought Rust was able to discern when you need to dereference or not automatically. I guess I don't understand why we need to dereference (or not dereference) in the two samples. The two examples I provided are commented with the specific bits of code I am wondering about.