【发布时间】:2016-01-17 04:50:00
【问题描述】:
我正在编写如下格式的函数:
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,但我很想看看是否还有其他方法。
【问题讨论】:
标签: vector rust lifetime ownership