Convert string to str, warns: borrowed value does not live long enough?

fn main(){
  let a = vec!["a".to_string(), "b".to_string(), "c".to_string()];
  let mut b: Vec<&str> = vec![];
  for each in a{
    b.push(each.as_str());       //borrowed value does not live long enough
  }
}

I want to iter the String vec, and collect each as str into another vec,
but it warns : borrowed value does not live long enough
how to deal with it?
thanks.

You're almost there, but you're iterating by consuming a, so each each goes out of scope after its loop iteration. If you iterate in a way that doesn't consume a, then you can still reference its contents:

fn main() {
    let a = vec!["a".to_string(), "b".to_string(), "c".to_string()];
    let mut b: Vec<&str> = vec![];
    for each in &a {
        b.push(each.as_str()); //borrowed value does not live long enough
    }
    dbg!(b);
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0c52ccfd7a58b0ac8177a344afed769f

2 Likes