Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract elements of a vector of strings in Rust?

Let's say I have the following code:

fn extract() -> Vec<String> {
    let data = vec!["aaa".to_string(), "bbb".to_string(), "ccc".to_string()];
    vec![data[0], data[2]]
}

In practice, I read data from a file.

Obviously, this doesn't compile because I'm pulling strings out of the vector data, leaving the vector in an undefined state. But, conceptually, it should work, because I'm not using data afterwards anyway.

I can use mem::replace, but this seems crazy:

fn extract() -> Vec<String> {
    let mut data = vec!["aaa".to_string(), "bbb".to_string(), "ccc".to_string()];
    let a = mem::replace(&mut data[0], "".to_string());
    let c = mem::replace(&mut data[2], "".to_string());
    vec![a, c]
}

How do I go about extracting specific elements from the vector without having to clone the strings?

like image 856
Listerone Avatar asked Oct 24 '25 04:10

Listerone


1 Answers

Vec has special methods for that. swap_remove, remove (warning, linear complexity), drain. For example,

fn extract() -> Vec<String> {
    let mut data = vec!["aaa".to_string(), "bbb".to_string(), "ccc".to_string()];
    // order does matter
    vec![data.swap_remove(2), data.swap_remove(0)]
}
like image 162
Laney Avatar answered Oct 26 '25 18:10

Laney