Default lifetime in struct definitions

I'm designing a library that has a type with a lifetime parameter 'a which is useful in certain cases, but in practice is almost always 'static:

struct Foo<'a> {
    p: PhantomData<&'a ()>
}

It would be nice if there was a way that users didn't have to specify Foo<'static> everywhere, but could instead just use Foo.

I would've expected specifying a default lifetime in the struct definition to work:

struct Foo<'a = 'static> {
    p: PhantomData<&'a ()>
}

// Similar to default generic parameter
struct Bar<T = &'static ()> {
    p: PhantomData<T>
}

Of course, one can work around this by making a type alias with a different name, but that would be unnecessarily confusing for the user (having to know the difference between Foo and FooWithLifetime<'a>).

Would appreciate pointers to previous discussion as to why default generic parameters are possible, but default lifetimes aren't.

There's previous discussion, I don't have any links off the top of my head. I one problem is that currently Foo (without the lifetime specified, for a struct Foo<'a>) already has a meaning; the same meaning as Foo<'_> for inferred or elided lifetimes. (Using this syntax is discouraged though since it hides lifetimes and in particular lifetime dependencies in method signatures like fn f(&self) -> Foo.)

1 Like

currently Foo (without the lifetime specified, for a struct Foo<'a>) already has a meaning; the same meaning as Foo<'_> for inferred or elided lifetimes

Ah yeah, forgot about that, that's unfortunate!

Would have been interesting to see how such a feature could have evolved though:

struct Foo<'a, 'b = 'a> {
    a: &'a i32,
    b: &'b i32,
}

Thanks for your help!

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.