0

I'll get error when compiled: 'returns value referencing data owned by the current function'

here's the code:

fn return_static_str(a: &'static str, b: &'static str) -> &'static str {
    format!("{} {}", a,b).as_str()
}

fn main() {
    let s = return_static_str("Hello ", "World!");
}

using return as_ref() get same issue.

6
  • Why not just return a String? Commented Dec 13, 2020 at 23:54
  • 2
    Does this answer your question? Return local String as a slice (&str) Commented Dec 14, 2020 at 0:07
  • 1
    This is impossible. The string you're creating is owned by the return_static_str function, so you can't return a reference to it. Return a String instead. Commented Dec 14, 2020 at 0:37
  • 1
    You might be able to use concat! instead if this is meant for use with literals. Commented Dec 14, 2020 at 7:36
  • 1
    @Lucretiel you can also make this a duplicate of more appropriate questions (I've added one) Commented May 9, 2022 at 23:55

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.