How can I take responsibility for a Vec element and replace it with something else?

I am writing a function in 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 an error "cannot exit indexed content", which makes sense. When I try to change it in such a way that itemis a link, I get an error when I try to set data[0]in None, which also makes sense.

Is there a way to do what I want to do? It seems to me that whether I want to return the link or not, I will have to take responsibility for the item from Vec.

I noticed that Vec has a method swap_removethat does almost what I want, except that it changes with the element already in Vec, and not with any arbitrary value as I would like. I know that I could just add NoneVec to the end and use it swap_remove, but I am interested to know if there is another way.

+4
source share
1 answer

Use std::mem::replace:

use std::mem;

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

replace significantly replaces the value in a particular place with another and returns the previous value.

+6
source

Source: https://habr.com/ru/post/1612167/


All Articles