1

I'm working with an external type (i.e., not my code), that has a bunch of &str members:

#[derive(Default, Clone)]
pub struct SomeExternalThingie<'a> {
    pub name: &'a str,
    pub description: Option<&'a str>,
    pub author: Option<&'a str>,
}

I want to make my own function which constructs and returns one of these things. I want to dynamically construct some of the strings used as members:

fn my_func_to_make_a_thingie<'a>(name: &'a str) -> MyThingie<'a> {
    let mydesc = format!("Hi, I'm your friendly neighborhood {}!",
        name);
    SomeExternalThingie {
        name: name,
        description: Some(mydesc.as_str()),
        ..Default::default()
    }
}

Of course, this won't compile, because the lifetime of mydesc ends when the function does. What's the best practice for dealing with a situation like this? I'm obviously new to Rust, but it seems like this will be a common scenario.

My only thought to change the return type to return both the desired structure and the storage for the string(s)... either by returning a tuple, or making a custom struct. This feels awkward, though, and I was wondering if there was a better way, or at least a convention of sorts.

For some context - the actual use case that prompted this was that I wanted to return a clap::App object. I wanted to do this mostly for organizational reasons - I know that in this case I can just include it in my main function, without the sub-function (even though it makes it longer than I'd like), and I'll probably end up doing this. However, this seems like a common pattern, and I wanted to learn the "Rust way" to deal with this.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Paul Molodowitch
  • 1,366
  • 3
  • 12
  • 29
  • You may also be interested in [How to convert a String into a &'static str](https://stackoverflow.com/a/30527289/155423). – Shepmaster Mar 04 '20 at 17:50
  • TL;DR the duplicates: no, you can't return a `&str` from that function. No, you can't return the `String` and a `&str` together. Instead, you need to ensure that `mydesc` is passed into `my_func_to_make_a_thingie`. [I might even make a struct](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b6da870045b36619d2d3862638ce47f3). – Shepmaster Mar 04 '20 at 17:56

0 Answers0