代码之家  ›  专栏  ›  技术社区  ›  Some Name

为什么index[]试图移动值,但直接调用index不会[重复]

  •  1
  • Some Name  · 技术社区  · 1 年前

    实例

    use std::ops::Index;
    
    fn test(v: &Vec<Vec<i32>>) {  
        let t = v.index(0); //ok
        let t = v[0]; //error, Vec<i32> does not implement Copy trait
    }
    

    Playground

    为什么会发生这种情况?如中所述 documentation :

    fn index(&self, index: I) -> &<Vec<T, A> as Index<I>>::Output

    执行索引( container[index] 活动

    所以应该是一样的。

    1 回复  |  直到 1 年前
        1
  •  0
  •   John Kugelman Michael Hodel    1 年前

    使用方括号时会出现隐藏的取消引用。这个 Index trait documentation 说:

    container[index] 实际上是的句法糖 *container.index(index)

    如果添加 * 到第一行,则会得到相同的错误消息:

    error[E0507]: cannot move out of a shared reference
     --> src/lib.rs:4:13
      |
    4 |     let t = *v.index(0);
      |             ^^^^^^^^^^^ move occurs because value has type `Vec<i32>`, which does not implement the `Copy` trait
      |
    help: consider removing the dereference here
      |
    4 -     let t = *v.index(0);
    4 +     let t = v.index(0);
      |
    

    Playground