4

I am trying to learn more about ownership. Here is some code that doesn't work because collect doesn't let you get a &mut String:

fn search(word: &str, data: &mut Vec<String>) {
    data = data
        .iter()
        .filter(|x| x.contains(word))
        .collect::<&mut Vec<String>>();
}

I think I could just return a cloned version, but is this the only/preferred way to do it?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

7

No, it is not possible. For this to be possible, collect would have to return a reference to something it created, and that's not possible.

You are looking for Vec::retain:

fn search(word: &str, data: &mut Vec<String>) {
    data.retain(|x| x.contains(word));
}

If you didn't want to mutate the passed-in data, you would indeed need to return a new Vec:

fn search<'a>(word: &str, data: &'a [String]) -> Vec<&'a String> {
    data.iter().filter(|x| x.contains(word)).collect()
}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366