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.

Lucretiel
  • 3,145
  • 1
  • 24
  • 52
Adriel Artiza
  • 327
  • 4
  • 12
  • Why not just return a String? – pretzelhammer Dec 13 '20 at 23:54
  • 2
    Does this answer your question? [Return local String as a slice (&str)](https://stackoverflow.com/questions/29428227/return-local-string-as-a-slice-str) – Ibraheem Ahmed Dec 14 '20 at 00: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. – Aloso Dec 14 '20 at 00:37
  • Maybe also [How to convert a String into a &'static str](https://stackoverflow.com/questions/23975391/how-to-convert-a-string-into-a-static-str) – Michael Anderson Dec 14 '20 at 06:38
  • 1
    You might be able to use [`concat!`](https://doc.rust-lang.org/std/macro.concat.html) instead if this is meant for use with literals. – EvilTak Dec 14 '20 at 07:36
  • 1
    @Lucretiel you can also make this a duplicate of more appropriate questions (I've added one) – Shepmaster May 09 '22 at 23:55

0 Answers0