A case of missed lifetime elision

Is it a good idea to infer lifetimes in a case like this one too?

fn foo(data1: &mut [bool], data2: &mut [u32]) -> &[u32] {

This means the compiler could infer that the lifetime of the output is the same as the lifetime of data2. I think this is correct in most cases, and where it's not correct you can add explicit lifetimes.

Why should it be tied to data2 by default? Why not data1?

Because in most cases you don't perform a transmutation from bools to u32s.

No, I do not think that adding such special-cased rules regarding arrays of primitive types is a good idea. The current rules for when lifetime elision is possible are very simple, and I think that adding weird special cases need to outweigh the costs of losing that simplicity.

5 Likes

Let's see past the fog, this is not a weird case: the output type is present only in one of the input arguments.

I don't think using the type information for eliding lifetimes is a good idea.

Why would it be desirable for the compiler to do this?

IMO lifetime elision is already magical enough (even too magical, in some places). Adding more elision rules just means you have to hold more things in your head while you're reading it.

3 Likes

I think this is a rather narrow case. Consider:

fn foo(data1: &mut SomeStruct, data2: &mut [u32]) -> &[u32]

It's no longer unambiguous, because SomeStruct could contain a field of type &mut [u32]. If you make a rule that elision can still work if SomeStruct doesn't currently have a &mut [u32] field, then adding such field would be a surprising semver-break.

5 Likes

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.