I mean something like:
fn minimum<'a, 'b>(x: &'a mut i32, y: &'b mut i32) -> &'min(a, b) mut i32 {
(x < y) ? x : y
}
We don't know which reference will be chosen at lifetime, but the compiler knows in which scope both references are still valid and the returned reference can be used safely.
A workaround that one can mention:
fn minimum<'a, 'b> where 'b: 'a (x: &'a i32, y: 'b i32) -> &'a i32 {
(x < y) ? x : y
}
isn't really the solution, because when calling a function we must handle both cases: when 'a: 'b
and 'b: 'a
This is what the compiler does automatically when you have a single unified lifetime:
fn minimum<'a>(x: &'a mut i32, y: &'a mut i32) -> &'a mut i32 {
if x < y { x } else { y }
}
This is the only memory safe option as the implementation of the function might choose either reference.
There is no "maximum" equivalent because to use it would not guarantee memory safety.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With