Can't imagine an example of impl<'a> Struct

Generic Implementations in the The Rust reference:

Generic parameters constrain an implementation if the parameter appears at least once in one of:

  • The implemented trait, if it has one
  • The implementing type
  • As an associated type in the bounds of a type that contains another parameter that constrains the implementation

Type and const parameters must always constrain the implementation. Lifetimes must constrain the implementation if the lifetime is used in an associated type.

I understand it like this: lifetime parameters in impl, for example impl<'a>, can exists and don't need be at one of 3 positions mentioned above, with exception of being used in an associated type, too.

And there is an example:

Example of an allowed unconstraining lifetime parameter:

impl<'a> Struct {}

Well, Is there a complete example of the impl<'a> Struct {}?
I can't imagine an impl<'a> T or impl<'a> T for trait where 'a is necessary

That is not valid Rust syntax. T is usually a convention for generic type parameters.

What it is saying is that this is okay (because lifetimes don't need to be constrained):

struct Foo;

impl<'a> Foo {
    fn bar(&self, x: &'a [u8]) -> &'a [u8] {
        x
    }
}

But this is not okay (because generic type parameters must be constrained):

struct Foo;

impl<T> Foo {
    fn baz(&self, x: T) -> T {
        x
    }
}

(playground example)

3 Likes

Here's a comment about unconstrained lifetime parameters.

I decided to allow such "unused" lifetimes even though, probably, they ought to be prohibited by RFC 447 because it wasn't clear to me what harm they could do. Given only methods, I don't think they really can do harm, though they are kind of pointless.

(Goes on to explain why they are problematic in associated types.)

And then:

This makes it illegal to have unconstrained lifetimes that appear in an associated type definition. Arguably, we should prohibit all unconstrained lifetimes -- but it would break various macros.

(Macros are a common motivation for allowing inert, superfluous things like unused parameters or trivial bounds.)

2 Likes

Seems 'a is a later bound in impl<'a> T, though I am not able to figure out a way to prove it.

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.