for-loop - 何时在 for 循环中使用引用?

标签 for-loop rust reference

有关向量的文档中的示例:

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时,你不想移动它。您想用 &vv.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/

相关文章:

rust - 为 Iterator+Clone : conflicting implementations 实现特征

C++ 独立引用 - 有什么用?

c++ - 我可以将每次移动引用的数组传递给 std::thread 吗?

c++ - 将引用返回值分配给非引用变量

java - 我该怎么做才能产生空间,从而使结果不同

Linux 庆典。 for循环和函数,用于添加数字

javascript - 在 Javascript 中迭代对象属性

linked-list - 不能直接将可变引用传递给自己

rust - 如何使用嵌入切片创建指向未调整大小类型的智能指针?

python - 在 Python 中使用 for 循环读取文件内容