TSK
TSK

Reputation: 751

Lifetime relationship between function arguments and return value

Question 1

What are the differences between these two functions in rust?

fn foo<'a>(x: &'a i32) -> &'a i32 {
    x
}
fn foo<'a: 'b, 'b>(x: &'a i32) -> &'b i32 {
    x
}

Question 2

What constraints are provided when the same lifetime parameter 'a is used among multiple function parameters and also in the return value?

fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
    ...
}

Upvotes: 2

Views: 144

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71450

Two differences as far as I can tell:

  • The second has two lifetimes that can be different, the first has only one.
  • The second's lifetimes are early-bound,the first's is late-bound. There are some differences, the main one being that you can't create a HRTB function pointer with early bound lifetime (let f: fn(&i32) -> &i32 = foo2; does not compile).

You almost always want (1), since it is less verbose and allows HRTB.

2.

The lifetime is the smallest of all. Ignoring the points at question 1, this is the same as:

fn foo<'a, 'b: 'a, 'c: 'a>(x: &'b i32, y: &'c i32) -> &'a i32 {
    ...
}

Upvotes: 3

Related Questions