Ben Pious
Ben Pious

Reputation: 4805

Reference with supertype lifetime can't be used for subtype lifetime

I'm struggling to understand how subtyping of lifetimes works. The name subtype suggests to me that if 'b is a subtype of 'a, then things of type 'a can be used anywhere something of type 'b will be used. And practically, in the context of lifetimes, I don't see what could go wrong from allowing that. However, the following code

fn test<'a, 'b: 'a>(first: &'a mut str, second: &'b mut str) -> &'b str {
    // do something to choose between the two arguments,
    // eventually pick first on some branch
    first
}

doesn't work, because "these two types are declared with different lifetimes... but data from first flows into second here."

So what would go wrong if this was allowed?

Upvotes: 1

Views: 74

Answers (1)

E_net4
E_net4

Reputation: 30082

So what would go wrong if this was allowed?

Your reasoning was inverted in this example: a constraint 'b: 'a reads as "'b lives as long as 'a". Since the output of test needs to live for at least as long as the lifetime 'b, 'a still represents a possibly incompatible lifetime, and first might actually not live long enough.

If you flip the lifetimes around, the code will then compile.

fn test<'a, 'b: 'a>(first: &'b mut str, second: &'a mut str) -> &'a str {
    first
}

Upvotes: 1

Related Questions