知识卡片
函数参数的生命周期契约
fn g(p: &i32) 等价于让参数拥有一个任意的 'a。调用者只需提供有效期足以覆盖本次调用的引用,编译器会推断合适的范围。若函数要把原引用保存进 static,则必须让签名要求 &'static i32,这样调用者传入的引用才具备运行全程有效的保证。g(&x) 可以借用局部变量,要求 'static 的接口会拒绝同一个 &x。生命周期写在契约里,因此可以根据函数签名推理保存行为。
关联阅读:[[借用有效范围的约束]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- References 由参数生命周期读出调用约束 · 查看原书依据
we were unable to write a function that stashed a reference in a global variable without reflecting that intention in the function’s signature.
参考来源
- 位置:《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#receiving-references-as-function-arguments`
- 结论依据:原文逐次修改 STASH 的写入函数,最后必须把参数标为静态生命周期,局部变量的调用例子展示了其后果。
- 原始内容:we were unable to write a function that stashed a reference in a global variable without reflecting that intention in the function’s signature.