知识卡片
返回引用沿用输入约束
fn smallest<'a>(v: &'a [i32]) -> &'a i32 把输入切片和输出引用绑定到同一个生命周期。若调用者在局部数组上调用它,拿到的是数组元素的借用。数组释放后仍要读取这个结果,会反向要求 'a 延伸到数组有效范围之外,因而编译失败。结果只用于输入数据仍然有效的位置时,检查器可以选出合适的 'a。
关联阅读:[[借用有效范围的约束]]、[[签名中的生命周期省略]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- References 返回借用时绑定输入和结果 · 查看原书依据
Lifetimes in function signatures let Rust assess the relationships between the references you pass to the function and those the function returns,
参考来源
- 位置:《Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)》第04章《References》|返回借用时绑定输入和结果,来源项目 `book-source`,`extracted/Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)/_epub-src/OEBPS/ch04.xhtml#returning-references`
- 结论依据:原文将最小元素函数的签名显式展开,并对比在输入数组作用域外和作用域内使用结果的两种调用。
- 原始内容:Lifetimes in function signatures let Rust assess the relationships between the references you pass to the function and those the function returns,