How can I take ownership of a Vec element and replace it with something else?

江枫思渺然 提交于 2019-12-22 03:53:08

问题


I am writing a function of the following format:

fn pop(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 a "cannot move out of indexed content" error, which makes sense. 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.

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.

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.


回答1:


Use std::mem::replace:

use std::mem;

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

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



来源:https://stackoverflow.com/questions/33204273/how-can-i-take-ownership-of-a-vec-element-and-replace-it-with-something-else

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!