示例:
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]
所以应该是一样的。
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);
|