You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中as_str()报错:临时值提前释放及生命周期问题咨询

Rust临时值生命周期问题解答

先看你写的代码:

fn main() {
    let s = String::from("hello").as_str();
    println!("slice: {}", s); 
}

编译器抛出的错误:

temporary value dropped while borrowed
creates a temporary value which is freed while still in userustcClick for full compiler diagnostic
main.rs(2, 43): temporary value is freed at the end of this statement
main.rs(3, 27): borrow later used here
main.rs(2, 5): consider using a `let` binding to create a longer lived value: `let binding = String::from("hello");
`, `binding`

疑问1:as_str()没有复制值吗?

没错,as_str()不会复制值。它的作用是从String生成一个&str类型的切片,这个切片只是借用原String内部的字符数据,没有创建新内存来存储字符串内容。说白了,&str就是指向原String数据的指针加上长度,完全依赖原String的存活才能有效。

疑问2:变量s存活至main函数结束,为何还会出现生命周期问题?

问题出在临时值的生命周期上:
String::from("hello")是个临时创建的String对象,它没被绑定到任何具名变量。在let s = String::from("hello").as_str();这行语句执行完后,这个临时String会被Rust自动销毁,占用的内存会被释放。

而s是这个临时String调用as_str()得到的切片,它的生命周期和临时String绑定。临时String销毁后,s就成了悬垂引用——指向已经被释放的内存。虽然s本身的作用域确实到main结束,但它引用的对象早没了,这就是编译器报错的原因。

解决方法很简单,按编译器提示把临时String绑定到具名变量上,让它的生命周期覆盖s的使用周期:

fn main() {
    let binding = String::from("hello");
    let s = binding.as_str();
    println!("slice: {}", s); 
}

内容的提问来源于stack exchange,提问作者Dolphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:32:35