Argument requires that `a` is borrowed for `'static`

Here is my code:

struct AStruct {
    S: String,
}

impl AStruct {
    pub fn new() -> AStruct {
        AStruct { S: "S".to_string() }
    }

    pub fn start(&'static mut self) {
        self.S = "started".to_string();
        yew::Callback::Callback(Rc::new(|result: Result<String, anyhow::Error>| {}));
    }
}

fn main() {
    let mut a: AStruct = AStruct::new();
    a.start();
}

I think I need to keep the start function parameter like this, but I get the following error:

error[E0597]: `a` does not live long enough
  --> src/main.rs:17:5
   |
17 |     a.start();
   |     ^^^^^^^^^
   |     |
   |     borrowed value does not live long enough
   |     argument requires that `a` is borrowed for `'static`
18 | }
   | - `a` dropped here while still borrowed

Is it possible to solve my problem without modifying start?

Not really. By putting 'static on the &mut self argument, the method can only be called on values that live forever. This should work:

pub fn start(&mut self) {
    self.S = "started".to_string();
    yew::Callback::Callback(Rc::new(|result: Result<String, anyhow::Error>| {}));
}

(Strictly speaking if you deliberately create a memory leak to ensure the memory lives forever, you would be able to call it once on that object, but only once, and the memory is permanently leaked until the process exits.)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.