Lifetimes and From Trait

Hello.
I don't know how to set a life times.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d7d07061f815ce0b956a0398b38cc5e5

You can't set a lifetime. Lifetimes are not values, they are a specification that the compiler verifies.

Here's how you would correctly specify the program you posted
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6bfdea910aa350f56e9be0fffd6bb124

You can read more about lifetimes in the Book here. While you are learning, I would also turn on #![forbid(elided_lifetimes_in_paths)] at the top of main.rs or lib.rs. This lint prevents you from writing ConfigA on it's own because it has a hidden lifetime parameter. You can explicitly elide them using '_ or tie it to a lifetime parameter, but you can't omit it (i.e either ConfigA<'_> or ConfigA<'some_lifetime>). This helps you figure out where the lifetimes are coming from, which I find to be extremely useful when debugging lifetime issues.

1 Like

Don't put references in structs. References are temporary borrows, and make structs anchored to a scope, which makes them nearly useless.

References in structs have some special uses, but more often than not it's a mistake to have a reference inside a struct.

Instead of:

#[derive(Serialize, Deserialize, PartialEq, Debug, Default)]
pub struct ConfigA<'a>
{
    pub header : &'a str,
    pub content : ContentA,
}

use

#[derive(Serialize, Deserialize, PartialEq, Debug, Default)]
pub struct ConfigA
{
    pub header : String,
    pub content : ContentA,
}