TSK
TSK

Reputation: 741

Lifetime bounds between function arguments

The code wants to constrain x and y to the same lifetime and uses a function to do so. But the compiler does not error when y is dropped. Does this mean lifetime bounds do not work between function arguments, irrespective of function return value?

static S: String = String::new();

// `x` and `y` have the same lifetime
fn foo<'a>(x: &'a String, y: &'a String) -> &'static String {
    if x == y {
        &S
    } else {
        &S
    }
}

fn main() {
    let z;
    let x = &"x".to_string();
    {
        let y = &"y".to_string();
        z = foo(x, y);
    } // drops `y`
    dbg!(x);
    dbg!(z);
}

Upvotes: 1

Views: 66

Answers (1)

user4815162342
user4815162342

Reputation: 154911

Requiring "the same" lifetime just means that the compiler must find some single lifetime that matches the scopes of objects referenced by x and y. It doesn't mean that they have to have identical scopes.

Since your function doesn't use the lifetime in return position, and they are non-mutable, it is not useful. A useful argument-only lifetime will typically involve mutation - for example:

fn append<'a>(v: &mut Vec<&'a str>, s: &'a str) {
    v.push(s);
}

If you tried to omit the lifetime here, the function wouldn't compile, because then it would allow appending short-lived references to a vector that expects e.g. static ones.

Upvotes: 4

Related Questions