我正在编写一个以下格式的函数:
fn pop<T>(data: &mut Vec<Option<T>>) -> Option<T> {
// Let the item be the current element at head
let item = data[0];
// and "remove" it.
data[0] = None;
item
}
当我尝试这样做时,我会得到一个错误,这是有道理的:
error[E0507]: cannot move out of index of `std::vec::Vec<std::option::Option<T>>`
--> src/lib.rs:3:16
|
3 | let item = data[0];
| ^^^^^^^ move occurs because value has type `std::option::Option<T>`, which does not implement the `Copy` trait
|
help: consider borrowing the `Option`'s content
|
3 | let item = data[0].as_ref();
| ^^^^^^^^^^^^^^^^
help: consider borrowing here
|
3 | let item = &data[0];
| ^^^^^^^^
当我试图将item
更改为引用时,我在尝试将data[0]
设置为None
时会出现错误,这也是有道理的。
有没有办法实现我的需求?在我看来,无论我是否想返回引用,我都必须拥有Vec中的元素。
我注意到Vec
有一个swap_remove
方法,它几乎完全符合我的要求,只是它与Vec
中的某个元素交换,而不是任意值。我知道我可以将None
附加到Vec
的末尾并使用swap_remove
,但我有兴趣看看是否有其他方法。
None
,则Option
中有一个特殊方法叫做take()
。在适用的情况下,我认为使用这个方法比使用replace()
更符合惯用法。 - Vladimir Matveev