ZhangHanDong / tao-of-rust-codes

《Rust编程之道》随书源码
https://ruststudy.github.io/tao_of_rust_docs/tao_of_rust/
MIT License
1.18k stars 170 forks source link

「第四章」4.2.3 内存泄漏与内存安全 代码清单4-21 #302

Closed Kreedzt closed 4 years ago

Kreedzt commented 4 years ago

来源: 微信读书


运行结果与书中不一致

Rust Playground

错误信息

error[E0515]: cannot return reference to local variable `a`
 --> src/main.rs:3:5
  |
3 |     &a
  |     ^^ returns a reference to data owned by the current function
ZhangHanDong commented 4 years ago

感谢反馈,我回头看看书上的示例。

单说你这个示例

fn foo<'a>() -> &'a str {
    let a = "hello".to_string();
    &a
}

fn main() {
    let x = foo();
}

你这个 foo 函数里的变量 a 是局部变量,它的引用本来就不能返回的。 你是否抄错代码了?

Kreedzt commented 4 years ago

我看微信书中就是局部的, 可能之后版本改动了?

ZhangHanDong commented 4 years ago

@Kreedzt 或者那个代码就是故意为了说明局部变量引用不能返回呢?看看上下文是不是,我手头没有书现在。

Kreedzt commented 4 years ago

以下为原文:

代码清单4-21:

fn foo<'a>() -> &'a str {
    let a = "hello".to_string();
    &a
}

fn main() {
    let x = foo();
}

... 当然, Rust 编译器是不会允许代码清单4-21编译通过的, 它会报如下错误

error[E0597]: `a` does not live long enough
|    &a
|       ^ does not live long enough
| }
ZhangHanDong commented 4 years ago

@Kreedzt 你好好看看原文。。。

这个例子就是要表达不能返回局部变量引用的。