14

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

Boann
  • 48,794
  • 16
  • 117
  • 146
aaalex88
  • 619
  • 4
  • 13

1 Answers1

13

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366