原因
第一次碰到这个错毫无头绪,简化代码是这样的
struct test_struct {}impl test_struct {fn return_string(&self) -> String {String::from("hello")}}fn main() {let t = test_struct{};let hello = t.return_string().as_str();println!("{}", hello);}
error[E0716]: temporary value dropped while borrowed--> src/main.rs:36:17|36 | let hello = t.return_string().as_str();| ^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement| || creates a temporary which is freed while still in use37 | println!("{}", hello);| ----- borrow later used here|= note: consider using a `let` binding to create a longer lived valueerror: aborting due to previous error
对于其他语言来说这样的写法再正常不过了,但对于rust来说却无法编译通过,来分析一下原因
return_string 返回的是一个owned value,as_str() 返回的是&str,&str是String的引用,也就是说String一定要比&str活的长,如果String比&str提早drop,那么&str就指向一个空值。那return_string()后,String的生命周期是什么呢?
如果这段代码这样写就很清楚了
let hello = {let __temp = t.return_string();__temp.as_str()}; // --> __temp die here
__temp在返回给hello就被drop了。
如何解决
解决办法很简单,写成两行就行了
fn main() {let t = test_struct{};let returnstr = t.return_string();let hello = returnstr.as_str();println!("{}", hello);}
let __temp = t.return_string();let hello = {__temp.as_str()}; // --> __temp lives long as hello
