Lifetimes on Trait Definitions

Hi all... I am running into some problems with lifetimes, probably because I am doing something silly. I am quite comfortable with rust and lifetimes, but this one has me stumped. What does it mean if i have a lifetime on a trait definition as follows:

pub trait Dog<'toy> {
    type Toy;

    fn play(toy: Self::Toy) {}
}

what is the lifetime <'toy> bound to? It needs this because some Toy's have lifetimes, so you would get something like:

impl Dog for Woofer {
    type Toy = ChewToy<'toy>; // the chewtoy only lasts so long

    fn play(toy: Self::Toy) {
        println!("woo: {:?}", toy);
    }
}

If i remove the lifetime on the trait and put it on the impl, i get a "unbound lifetime" error. However when i try to use this in a more complex way, i am getting other lifetime errors. I am just looking to understand what it means exactly to have the lifetime defined on the trait definition (as i'm running into other errors i believe because of this).

As an alternative, if i was to change the trait to remove the lifetime:

pub trait Dog<T> {
    fn play(toy: T) {}
}

and then the impl can be:

impl<'toy> Dog<ChewToy<'toy>> for Woofer {

    fn play(toy: ChewToy<'toy>) {
        println!("woo: {:?}", toy);
    }
}

There is no way to know the type ChewToy from Woofer as it is not an associated type? Eg. i cant go Woofer::Toy anymore.

I didn't know you could do that... but I would expect a lifetime parameter on a trait has a meaning that is analogous to that of a type parameter on a trait: it means the trait you're describing is a actually a family of traits, and any implementation will have to provide a lifetime to satisfy the parameter.

It's not clear how useful or common that would be... maybe you've got a trait that is only valid within some context, but the validity of that context is external to the type you're implementing the trait on?

What are you actually trying to do? You probably don't want to put actually put a lifetime on the trait this way.

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