知识卡片
函数局部数据宜移交所有权
函数内新建的 String 会随局部所有者离开作用域而被释放。把其切片返回给调用方会留下无效引用,添加任何生命周期都不能改变这个事实。若需要把新文本交出去,让函数直接返回 String,调用者将成为新所有者。
相关卡片 [[返回借用受共同范围约束]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 泛型类型、trait 与生命周期 Lifetime Annotation Syntax · 查看原书依据
The problem is that result goes out of scope and gets cleaned up at the end of the longest function. We’re also trying to return a reference to result from the function. There is no way we can specify lifetime parameters that would change the dangling reference, and Rust won’t let us create a dangling reference.
参考来源
- 位置:《The Rust Programming Language(第2版)》第10章 泛型类型、trait 与生命周期(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c10.xhtml`,块 0271)
- 结论依据:原文解释局部 result 不能作为返回借用,给出返回自有数据的修复方向。
- 原始内容:The problem is that result goes out of scope and gets cleaned up at the end of the longest function. We’re also trying to return a reference to result from the function. There is no way we can specify lifetime parameters that would change the dangling reference, and Rust won’t let us create a dangling reference.