为什么index[]会尝试移动值,但直接调用index却不会

问题描述 投票:0回答: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
}

游乐场

为什么会发生这种情况?如文档中指定:

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

执行索引 (

container[index]
) 操作

所以应该是一样的。

rust vector indexing slice move-semantics
1个回答
0
投票

使用方括号时会隐藏取消引用。

Index
特质文档说:

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);
  |
© www.soinside.com 2019 - 2024. All rights reserved.