【问题标题】:When to use references in for loops?何时在 for 循环中使用引用?
【发布时间】:2020-05-17 00:29:10
【问题描述】:

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

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

【问题讨论】:

    标签: for-loop rust reference


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-26
      • 2017-02-02
      • 2021-12-08
      • 2013-12-21
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      相关资源
      最近更新 更多