-2

I am trying to convert a String to an &str. But the problem is that rust will always throw this error:

error[E0515]: cannot return value referencing local variable `contents`
   --> src/utils.rs:111:5
    |
72  |         let contents = &contents[..];
    |                         -------- `contents` is borrowed here
...
111 |     result
    |     ^^^^^^ returns a value referencing data owned by the current function

For more information about this error, try `rustc --explain E0515`.

How do i convert the variable into an &str?

  • 1
    Just return a `String` it's what you want in 99.9% of all cases. See also [Return local String as a slice (&str)](https://stackoverflow.com/questions/29428227/return-local-string-as-a-slice-str/74537374) – cafce25 Mar 08 '23 at 15:58
  • The goal of the code is to return a `Vec<&str>`. I cant just return a string here. – inyourface3445 Mar 08 '23 at 16:01
  • 6
    Then you want to return `Vec` you can't create references without an owner unless you leak memory. – cafce25 Mar 08 '23 at 16:02
  • 1
    Your code is way too incomplete to provide any specific help, all we can say is that you're trying to return a reference to a `String` which was created or moved in the current function, which is not allowed (ish, you could always leak the string after all). Either find a way not to do that, or change your return type to return the owned data. – Masklinn Mar 08 '23 at 16:03
  • I just made it return a vector of strings, and that fixed everything. – inyourface3445 Mar 08 '23 at 16:08
  • I would go with this rule of thumb - when you want to work on a string-like thing (function argument), use a `&str`. When you want to _store_ a string-like thing, use a `String`. Exceptions exist both ways, but it works quite a lot of the time. – Kevin Anderson Mar 08 '23 at 17:07

1 Answers1

0

It turned out that it was better to return Vec<String> then Vec<&str>. That fixed my issue. Thanks to cafce25 for giving the idea.

  • 1
    A safe rule of thumb if you're struggling with rust lifetimes is to write functions that take references and return values (so in this case, take `&str`s and return `String`s) – Roger Filmyer Mar 08 '23 at 18:28