为什么我不能从函数返回字符串的链接,但我可以切片吗?

Ome*_*gon 2 rust

我正在阅读最初的 Rust 指南。那里表明不可能从函数返回对字符串的引用。

fn dangle() -> &String { // dangle returns a reference to a String

    let s = String::from("hello"); // s is a new String

    &s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped. Its memory goes away.
  // Danger!
Run Code Online (Sandbox Code Playgroud)

但我对下一章的示例感到困惑,其中切片的链接是从函数返回的:

fn first_word(s: &String) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}
Run Code Online (Sandbox Code Playgroud)

我明白为什么不可能从函数返回到字符串的链接,但为什么可以以这种方式返回到切片的链接?因为字符串本身是通过引用传递的,或者这不是原因?我是初学者,如果有人帮助我理解这里发生的事情,我会很高兴。

tad*_*man 6

在第一种情况下,您将返回对本地范围的临时变量的引用。这不好,如前所述,该值将被删除,这会使任何引用无效。

在第二种情况下,您将返回对参数中提供的数据的引用,其生命周期在函数之外,因此没问题。返回值的生命周期就是调用者参数的生命周期,无论它是什么。