Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get & replace a value in Rust Vec?

What I'm looking for is a replace method:

pub fn replace(&mut self, index: usize, element: T) -> T

Replaces an element at position index within the vector and returns the existing value.

Calling remove+insert seems wasteful to me.

like image 609
Guy Korland Avatar asked Aug 11 '19 10:08

Guy Korland


People also ask

Will there be a 7th season of how do you get away?

If you're wondering whether this twisty series is renewed for Season 7, sadly, the answer is no. ABC decided Season 6 would be the final season of the show, which means the Season 6 finale was the series finale, and we won't be getting another year of Annalise Keating (Viola Davis).

Where can I watch how do you get away season 8?

Right now you can watch How to Get Away with Murder on Netflix. You are able to stream How to Get Away with Murder by renting or purchasing on Amazon Instant Video, iTunes, Vudu, and Google Play.


1 Answers

You can emulate this easily on any container that gives you mutable references to its elements using std::mem::replace:

fn main() {
    let mut v = vec![1, 2, 3, 4, 5, 6];

    let got = std::mem::replace(&mut v[3], 42);

    println!("v = {:?}", v);
    println!("got = {:?}", got);
}

(Permalink to the playground)

Result:

v = [1, 2, 3, 42, 5, 6]
got = 4

In the case of Vec, should you want to replace a range of elements, you would be interested in the method splice, which replaces values, and returns the old one. However, it is likely to be less efficient for a single value.

like image 194
mcarton Avatar answered Sep 23 '22 23:09

mcarton