如何获得Vec元素的所有权并将其替换为其他元素? [英] How can I take ownership of a Vec element and replace it with something else?
问题描述
我正在编写以下格式的函数:
I am writing a function of the following format:
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
}
当我尝试执行此操作时,我得到一个有意义的错误:
When I try to do this, I get an error which makes sense:
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
时出现错误,这也是有道理的.
When I try to change it such that item
is a reference, I get an error when I try to set data[0]
to None
, which also makes sense.
我可以通过某种方式完成自己想做的事情吗?在我看来,无论我是否要返回引用,我都必须从Vec中获取该元素的所有权.
Is there some way I can do what I want to do? It seems to me that, whether I want to return a reference or not, I'm going to have to take ownership of the element from the Vec.
我注意到Vec
有一个swap_remove
方法,该方法几乎可以实现我想要的功能,只是它与Vec
中已经存在的元素交换,而不是我想要的任何任意值.我知道我可以将None
附加到Vec
的末尾并使用swap_remove
,但是我有兴趣查看是否还有另一种方法.
I noticed that Vec
has a swap_remove
method, which does almost exactly what I want, except that it swaps with an element already in the Vec
, not with any arbitrary value as I would like. I know that I could just append None
to the end of the Vec
and use swap_remove
, but I'm interested in seeing if there's another way.
推荐答案
使用 replace
本质上是将特定位置的值替换为另一个位置,并返回先前的值.
replace
essentially replaces the value in a particular location with another one and returns the previous value.
另请参阅:
这篇关于如何获得Vec元素的所有权并将其替换为其他元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!