gpt4 book ai didi

for-loop - 什么时候在for循环中使用引用?

转载 作者:行者123 更新时间:2023-12-03 11:45:34 27 4
gpt4 key购买 nike

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

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需要作为引用。 let third: i32 = v[2]似乎也可以正常工作。使它成为引用可以实现什么?

相似地:
let v = vec![100, 32, 57];
for i in &v {
println!("{}", i);
}

为什么是 in &v而不是 in v

最佳答案

let third: 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com