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

How do i fix this issue?

fn main() {

    let config = get_config();
    let automation = Automation::new(&config);

    println!("{}", automation.config.name);

}

struct Config {
    pub name: String
}


fn get_config() -> Config {
    Config {
        name: "test".to_string()
    }
}

struct Automation {
    pub config: &'static Config
}

impl  Automation {
    pub fn new(config: &'static Config) -> Self {
        Automation {
            config
        }
    }
}

When i compile this i get this error
error[E0597]: `config` does not live long enough
 --> src/main.rs:4:38
  |
4 |     let automation = Automation::new(&config);
  |                      ----------------^^^^^^^-
  |                      |               |
  |                      |               borrowed value does not live long enough
  |                      argument requires that `config` is borrowed for `'static`
...
8 | }
  | - `config` dropped here while still borrowed

I am newb to rust...am i doing something wrong?

In main(), config's lifetime isn't static, while Automation::new requires the static lifetime.

You can make Automation accept it's own lifetime:

struct Automation<'a> {
    pub config: &'a Config
}

impl<'a> Automation<'a> {
    pub fn new(config: &'a Config) -> Self {
        Automation {
            config
        }
    }
}

Thank you that helped

1 Like

BTW: lifetimes lock structs to the scope in which the temporary borrow has been created. 99% of the time you want structs to own data:

struct Automation {
    pub config: Config
}

If you want to store Config by reference, then use Box<Config> (storing things by reference, and temporarily borrowing with references are different things in Rust).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.