Struct reference fields and lifetimes

pub struct Test<'a> 
{
    item_ : Arc<&'a Item>
}

impl<'a> Test<'a>
{
    pub fn new(item : Arc<&'a Item>) -> Self
    {
        return Self {
            item_ : item
        };
    }
}

impl<'a> ITest for Test<'a>
{
    fn handle_event(&self, event : &mut Event) -> ()
    {        
        event.do_something(&self.item_);
    }
}

How do I address the lifetime issue when I try implement the ITest trait? I get the following error:

error[E0478]: lifetime bound not satisfied
note: but lifetime parameter must outlive the static lifetime

Can someone help me understand the issue and also guide me to a solution?

It's not possible to answer this question with the information you've given. Ideally you'd reproduce the problem in https://play.rust-lang.org/ and link it here, or link to a repository where you hit the problem if it's too hard to minimise. You should also include the full error message.

Anyway, Arc<&'a Item> is suspicious. The point of Arc (and Rc) is to provide shared ownership. They do this via reference counting, and indirection (i.e. they heap allocate the inner value and only pass around a pointer to it). Combined with the fact that one uses Arc (and Rc) when the code and data is not structured in a clean, tree-like fashion, it's almost always the case that Arc (and Rc) are a workaround for avoiding lifetimes.

Thus, in real code, you almost never see an explicit Arc<&_> type. It is likely that you misunderstand what references are for – maybe you are thinking that they are for storing data "by reference", but that's not what they do. What do you think you can achieve with Arc<&Item>? There is likely a better/correct way of doing what you are trying to do.

3 Likes

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.