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.