Home > Software engineering >  Lifetime for ref to generic in trait
Lifetime for ref to generic in trait

Time:09-24

I'm trying to require a generic type to be indexable by const ref to another generic:

struct A<T, I> where T: Index<&I> {
    t: T,
    some_more_uses_of_I...
}

it does not compile asking me to provide a lifetime for &I. When I change it into &'_ I compiler complains that "'_ cannot be used here" and "'_ is a reserved lifetime name". How can I make it work? To my understanding there is no real need for the lifetime, the reference must be alive only during execution of [] and I belive I shouldn't tie it to any other object.

CodePudding user response:

Without knowing exactly how you're using this struct, its hard to say. But it sounds like you could use a higher-ranked trait bound such that the constraint is generic over the lifetime:

struct A<T, I> 
where 
    T: for<'a> Index<&'a I>
{
    t: T,
    some_more_uses_of_I...
}

CodePudding user response:

This should be compile

struct A<'a, T, I>
    where T: Index<&'a I> {
        t: T
    }

You can see more about in https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-annotations-in-struct-definitions

  • Related