Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to choose the lesser of two lifetimes?

Tags:

rust

lifetime

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

like image 890
aaalex88 Avatar asked Feb 28 '19 12:02

aaalex88


1 Answers

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:

  • When is it useful to define multiple lifetimes in a struct?
  • Why would you ever use the same lifetimes for references in a struct?
  • How can I port C++ code that uses the ternary operator to Rust?
like image 188
Shepmaster Avatar answered Nov 05 '22 09:11

Shepmaster