有关向量的文档中的示例:
let v = vec![1, 2, 3, 4, 5];
let third: &i32 = &v[2];
println!("The third element is {}", third);
match v.get(2) {
Some(third) => println!("The third element is {}", third),
None => println!("There is no third element."),
}
我不明白为什么third
需要作为引用。 letthird: i32 = v[2]
似乎也同样有效。使其成为引用可以实现什么目的?
同样:
let v = vec![100, 32, 57];
for i in &v {
println!("{}", i);
}
为什么它在&v
中而不是在v
中?
最佳答案
letthird: i32 = v[2]
之所以有效,是因为 i32
实现了 Copy
特征。索引向量时它们不会被移出,而是被复制。
当你有一个非Copy
类型的向量时,情况就不同了。
let v = vec![
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string(),
"5".to_string(),
];
let third = &v[2]; // This works
// let third = v[2]; // This doesn't work because String doesn't implement Copy
关于循环的第二个问题,for循环是IntoIterator
的语法糖,它移动并消耗。
所以,当你需要在循环后使用v
时,你不想移动它。您想用 &v
或 v.iter()
来借用它。
let v = vec![100, 32, 57];
for i in &v { // borrow, not move
println!("{}", i);
}
println!("{}", v[0]); // if v is moved above, this doesn't work
关于for-loop - 何时在 for 循环中使用引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61845445/