0

In rust, I have a function that generates a vector of Strings, and I'd like to return this vector along with a reference to one of the strings. Obviously, I would need to appropriately specify the lifetime of the reference, since it is valid only when the vector is in scope. However, but I can't get this to work.

Here is a minimal example of a failed attempt:

fn foo<'a>() -> ('a Vec<String>, &'a String) {
    let x = vec!["some", "data", "in", "the", "vector"].iter().map(|s| s.to_string()).collect::<Vec<String>>();
    (x, &x[1])
}

(for this example, I know I could return the index to the vector, but my general problem is more complex. Also, I'd like to understand how to achieve this)

Amir
  • 888
  • 9
  • 18

1 Answers1

2

Rust doesn't allow you to do that without unsafe code. Probably your best option is to return the vector with the index of the element in question.

This is conceptually very similar to trying to create a self-referential struct. See this for more on why this is challenging.

at54321
  • 8,726
  • 26
  • 46