2020-09-27

How can I get a &str returned here?

When I try to run this:

struct Person {
    name: String,
}

impl Person {
    fn new(name: String) -> Self {
        Person {
            name: name,
        }
    }
    
    fn name(&self) -> &str {
        self.name.as_str()
    }
}

thread_local! {
    static NAMED_THING: Person = Person::new("John".to_string());
}

fn main() {
    let s = NAMED_THING.with(|n| n.name());
    println!("The name is {}", s);
}

it tells me

error: lifetime may not live long enough
  --> src/main.rs:22:34
   |
22 |     let s = NAMED_THING.with(|n| n.name());
   |                               -- ^^^^^^^^ returning this value requires that `'1` must outlive `'2`
   |                               ||
   |                               |return type of closure is &'2 str
   |                               has type `&'1 Person`

I could do instead:

let s = NAMED_THING.with(|n| n.name().to_owned());

But it seems pretty wasteful to clone that string every time?

Playground



from Recent Questions - Stack Overflow https://ift.tt/343dp1b
https://ift.tt/eA8V8J

No comments:

Post a Comment