我该如何拥有一个Vec元素并将其替换为其他内容?

22

我正在编写一个以下格式的函数:

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,但我有兴趣看看是否有其他方法。

1个回答

30

19
顺便提一下,如果要将可选值替换为 None,则 Option 中有一个特殊方法叫做 take()。在适用的情况下,我认为使用这个方法比使用 replace() 更符合惯用法。 - Vladimir Matveev
7
我无法相信vec本身没有一种方法。 - ditoslav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接