Default lifetime parameter in type alias?

In a type alias definition, Rust lets you set a default value for generic type parameters, as follows:

type MyResult<T=String> = Result<T, MyError>;

Is it possible to do the same with generic lifetime parameters?

type MyRefResult<'a='static, T> = Result<&'a T, MyError>;

Seems like this is completely syntactically invalid right now. I'd like to be able to write MyRefResult<T> instead of MyRefResult<'static, T> because the vast majority of the time, the lifetime is 'static.

I suspect the problem is that lifetime parameters are allowed to be omitted for inference, even though it's recommended to use MyRefResult<'_, T> in that case (the elided-lifetimes-in-paths lint). So MyRefResult<T> would be ambiguous whether you wanted it to be inferred, or wanted the default 'static.


Gankra's Defaults Affect Inference discusses this problem directly; although it focuses on type defaults for generic functions, it applies equivalently to any lifetime defaults since lifetimes are always inferred[1] when omitted.

The suboptimal workaround is to have separate aliases, e.g.

type MyResultRef<'a, T, E=MyError> = StdResult<Cow<'a, E>;
type MyStaticOwn<T, E=MyError> = MyResultRef<'static, T, E>;
// or whatever bikeshed flavor makes sense

If we ever manage to find and implement a satisfactory resolution to inference-influencing defaults, perhaps we'll be able to allow defaulted lifetimes in the future. Or perhaps, if we can drive consensus on making the should-use-'_ lint warn-by-default when specifying a generics list, make it so lifetime defaults are allowed and apply in future editions when writing MyRefResult<T> but keep the inference-driven behavior when writing MyRefResult or MyRefResult<'_, T>.

  1. Though sometimes inference is setting it to the specific elided lifetime, such as in function signatures or impl receivers. ↩ī¸Ž