Lifetime issue with 'indicate the anonymous lifetime: `<'_>`'

Thanks all for the help so far.
I have this below struct, and I need it to implement display. It seems that, because I added a lifetime param to Blockchain, the display function no longer compiles, and my error is

152 | impl Display for Blockchain {
    |                  ^^^^^^^^^^- help: indicate the anonymous lifetime: `<'_>`
    |
    = note: assuming a `'static` lifetime...

#[derive(Serialize, Deserialize, Clone)]
pub struct Blockchain <'lt> {
    #[serde(skip)]
    pub trans_observers: HashMap<&'lt Transaction, OnTransactionSettled>,
    #[serde(skip)]
    pub block_observers: Vec<OnBlockEvent>,
    pub genesis_block: GenesisBlock,
    pub blocks: Vec<Block>,
}

impl Display for Blockchain {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let json = serde_json::to_string_pretty(&self).expect("json format error");
        write!(f, "{}", json)
    }
}

I spent almost an hour now on this. Can someone explain to me what's going on?

It’s telling you to write that code, <‘_> at the position it’s showing, indicating an anonymous lifetime being passed to the type in that impl block.

1 Like

OMG! I swear I did this and it then told me it was unnecessary!!!!

I am going to go hide in shame!

Coding can be cruel, there are always more ways to make the compiler mad.

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.