如何获得 Vec 元素的所有权并将其替换为其他内容? [英] How can I take ownership of a Vec element and replace it with something else?

查看:16
本文介绍了如何获得 Vec 元素的所有权并将其替换为其他内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

使用 std::mem::replace:

use std::mem;

fn pop<T>(data: &mut Vec<Option<T>>) -> Option<T> {
    mem::replace(&mut data[0], None)
}

replace 本质上是用另一个位置替换特定位置的值并返回前一个值.

replace essentially replaces the value in a particular location with another one and returns the previous value.

另见:

这篇关于如何获得 Vec 元素的所有权并将其替换为其他内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆