0

I want to have a function which owns its parameter, and returns ownership along with references to that parameter - but I can't figure out how to annotate the lifetime for rust to allow it:

fn line_refs(s: String) -> (String, Vec<&str>) {
  (s, s.lines().collect())
}

Rust requires I add lifetime to the refs, but I'm not sure how I indicate that their lifetime is associated with s.

feature_engineer
  • 1,088
  • 8
  • 16
  • 2
    Does this answer your question? [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct), tuples are just `struct`s without a name. – cafce25 Jan 10 '23 at 07:49
  • Moving `s` back to the caller invalidates all of the references, which is why you cannot do this in this way. Note that this kind of code _would_ compile under C++, but then would cause undefined behavior during runtime. Rust is protecting you. – cdhowie Jan 10 '23 at 08:00
  • @cdhowie I get that the address of s changes and thus references to s are invalidated. But a String is actually a smart pointer, and the data it points to is still at the same address, so it should still be valid after the move - how can I keep references to that underlying data? – feature_engineer Jan 10 '23 at 08:27
  • @feature_engineer You can't without using unsafe code. See the linked duplicate. (Note also that nothing precludes a "small string optimization" in `String`'s implementation, and then what you ask would be _very_ problematic, because the returned references very well could point into `s`.) – cdhowie Jan 10 '23 at 09:05

0 Answers0