为什么借用字符串文字可以通过伪造一生而比其所有者更长寿?

Paw*_*mar 4 lifetime rust borrow-checker borrowing

我明白,借用它不能比它指向的东西的存在更长久,以消除悬空指针.

通过伪造生命期,借用或别名可以超过所有者:

fn main() {
    let e;
    let first = "abcd";
    {
        let second = "defgh";
        e = longest(first, second);
    }
    println!("{}", e);
}

fn longest<'a>(first: &'a str, second: &'a str) -> &'a str {
    if first.len() > second.len() {
        first
    } else {
        second
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

defgh
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,变量e具有比具有更长的寿命second变量并明确了firstsecond变量寿命是不同的.

e使用longest(first, second)它初始化时,得到second变量,其函数调用的生命周期是伪造的,因为它等于first但是它被限制在块中并且被分配给e它将比它更长second.为什么这样好?

Mar*_*cus 8

这是因为这两者都具有'static寿命.

这是一个不起作用的例子,因为str这里没有像程序一样生活在程序的生命&'static str中.唯一的变化是以下行:let second = String::from("defgh");以及传递给最长函数的下一行.

fn main() {
    let e;
    let first = "abcd";
    {
        let second = String::from("defgh");
        e = longest(first, &second);
    }
    println!("{}", e);
}

fn longest<'a>(first: &'a str, second: &'a str) -> &'a str {
    if first.len() > second.len() {
        first
    } else {
        second
    }
}
Run Code Online (Sandbox Code Playgroud)

这是错误:

error[E0597]: `second` does not live long enough
 --> src/main.rs:6:28
  |
6 |         e = longest(first, &second);
  |                            ^^^^^^^ borrowed value does not live long enough
7 |     }
  |     - `second` dropped here while still borrowed
8 |     println!("{}", e);
  |                    - borrow later used here
Run Code Online (Sandbox Code Playgroud)

更多信息可以在Static - Rust By Example中找到