Rust 生命周期
核对 Rust 借用检查器防止垂悬引用的生命周期区间原理、函数生命周期注解 'a、结构体引用字段与方法省略规则、'static 静态生命周期及泛型特性协同用法。
学完这一章,你能够
- 核对 Rust 借用检查器防止垂悬引用的生命周期区间原理、函数生命周期注解 'a、结构体引用字段与方法省略规则、'static 静态生命周期及泛型特性协同用法。
垂悬引用与生命周期区间校验
生命周期(Lifetime)是 Rust 借用检查器在编译期确保所有引用始终有效的核心机制。当外层变量 `r`(生命周期 `'a`)借用内层代码块局部变量 `x`(更短的生命周期 `'b`)并在内层块结束后继续使用 `r` 时,`x` 已被释放,形成垂悬引用;编译器比较区间后发现 `'b` 短于 `'a`,因此拒绝编译。本站离线区间检查器核对 `r('a)` 超出 `x('b)` 范围被拒、移入内层块后通过的规则。
对多引用参数函数 `fn longer(s1: &str, s2: &str) -> &str` 而言,返回值可能来自 `s1` 或 `s2`,借用检查器无法仅凭签名判断返回引用应绑定到哪一个输入参数的存活期(注:若调用方传入堆分配的 `String` 切片且其中一个在内层作用域结束时释放,外层持有返回值就会悬垂;而双引号字面量本身其实拥有 `'static` 生命周期)。因此函数签名必须显式交代输入与输出引用的生命周期关系。
生命周期注解语法与函数改造
生命周期注解以单引号加小写标识符表示(如 `&'a i32`、`&'a mut i32`),它不改变任何值的真实存活时间,只向编译器声明多个引用之间的存活约束关系。将函数改写为 `fn longer<'a>(s1: &'a str, s2: &'a str) -> &'a str` 后,返回值被约束为不超过 `s1` 与 `s2` 两者生命周期的交集(较短者),调用方在有效作用域内使用 `longer("rust", "ecmascript")` 即可顺利输出 `ecmascript is longer`。离线校验器已核对未标注二参函数的省略失败原因以及交集区间内外使用判定。
结构体引用字段、省略规则、'static 与综合用法
结构体若包含切片引用字段,必须在类型头声明生命周期参数:`struct Str<'a> { content: &'a str }`,表明结构体实例绝不能活得比 `content` 所指向的数据更久。在 `impl<'a> Str<'a>` 上定义方法 `fn get_content(&self) -> &str` 时,得益于稳定版 Rust 的三条生命周期省略规则(含 `&self` 或 `&mut self` 的方法默认将 `self` 的生命周期赋予输出引用),返回值上的 `'a` 可安全省略,显式写出亦完全合法。
特殊生命周期 `'static` 代表引用可在整个程序运行期间持续有效,所有字符串字面量的完整类型均为 `&'static str`。在实际工程中,生命周期参数常与泛型参数、特性约束协同出现在同一签名中,例如 `fn longest_with_an_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str where T: Display`(生命周期参数写在泛型列表最前)。离线校验器已核对方法省略规则、`&'static str` 覆盖结构体作用域以及综合公告函数的输出。
运行离线 Python 校验:Rust 生命周期区间检查、省略规则、'static 与泛型协同
"""Offline Rust semantic verifier for Chapter 22: Lifetimes (borrow scope checker, elision rules, 'static)."""
from dataclasses import dataclass
import json
@dataclass(frozen=True)
class ScopeInterval:
name: str
start_line: int
end_line: int
def outlives(self, other: "ScopeInterval") -> bool:
return self.start_line <= other.start_line and self.end_line >= other.end_line
def check_borrow(owner_scope: ScopeInterval, ref_use_scope: ScopeInterval) -> tuple[bool, str]:
if owner_scope.outlives(ref_use_scope):
return True, "ok"
return False, f"`{owner_scope.name}` does not live long enough for `{ref_use_scope.name}`"
def elide_fn_lifetimes(param_refs: list[str], has_self_ref: bool, output_ref: bool) -> tuple[bool, str]:
"""Implements Rust's three lifetime elision rules."""
if not output_ref:
return True, "no_output_ref"
if has_self_ref:
return True, "elided_to_self_lifetime"
if len(param_refs) == 1:
return True, f"elided_to_{param_refs[0]}"
return False, "missing_lifetime_specifier_ambiguous_inputs"
def longer(s1: str, s2: str) -> str:
return s2 if len(s2) > len(s1) else s1
def longest_with_announcement(x: str, y: str, ann: str) -> tuple[str, str]:
msg = f"Announcement! {ann}"
res = x if len(x) > len(y) else y
return msg, res
def run_cases() -> list[dict]:
cases = []
# Case 1: Dangling reference detection ('a outlives 'b -> rejected)
r_scope = ScopeInterval("r('a)", start_line=2, end_line=9)
x_scope = ScopeInterval("x('b)", start_line=4, end_line=6)
ok_dangle, msg_dangle = check_borrow(x_scope, r_scope)
inner_use = ScopeInterval("r_inner", start_line=5, end_line=6)
ok_valid, _ = check_borrow(x_scope, inner_use)
actual_1 = {
"dangling_rejected": not ok_dangle,
"error_mentions_lifetime": "does not live long enough" in msg_dangle,
"inner_scope_accepted": ok_valid,
}
expected_1 = {
"dangling_rejected": True,
"error_mentions_lifetime": True,
"inner_scope_accepted": True,
}
cases.append(dict(
name="dangling_reference_scope_check",
summary="Verify outer borrow 'a outliving inner value 'b is rejected while inner-scope use succeeds",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Function lifetime annotation and elision rules
unannotated_ok, unannotated_reason = elide_fn_lifetimes(["s1", "s2"], has_self_ref=False, output_ref=True)
# With explicit <'a>, returned lifetime is intersection min(s1, s2)
s1_scope = ScopeInterval("s1", 1, 10)
s2_scope = ScopeInterval("s2", 3, 6)
min_scope = ScopeInterval("min(s1,s2)", max(s1_scope.start_line, s2_scope.start_line), min(s1_scope.end_line, s2_scope.end_line))
use_inside_ok, _ = check_borrow(min_scope, ScopeInterval("print_inside", 4, 5))
use_outside_ok, _ = check_borrow(min_scope, ScopeInterval("print_outside", 4, 8))
actual_2 = {
"unannotated_longer_rejected": not unannotated_ok,
"unannotated_reason": unannotated_reason,
"longer_value": longer("rust", "ecmascript"),
"use_inside_accepted": use_inside_ok,
"use_outside_rejected": not use_outside_ok,
}
expected_2 = {
"unannotated_longer_rejected": True,
"unannotated_reason": "missing_lifetime_specifier_ambiguous_inputs",
"longer_value": "ecmascript",
"use_inside_accepted": True,
"use_outside_rejected": True,
}
cases.append(dict(
name="longer_fn_annotation_and_intersection",
summary="Verify two-&str input elision ambiguity, longer<'a> result, and shortest-input intersection check",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Struct<'a> with &str field, method elision rule 3, 'static, and generics+trait+lifetime
method_ok, method_rule = elide_fn_lifetimes(["&self"], has_self_ref=True, output_ref=True)
static_scope = ScopeInterval("'static", 0, 10**9)
struct_scope = ScopeInterval("Str<'a>", 10, 50)
static_ok, _ = check_borrow(static_scope, struct_scope)
ann_msg, ann_longest = longest_with_announcement("rust", "ecmascript", "compare lengths")
actual_3 = {
"struct_content": "s.content = string_slice",
"method_elision": [method_ok, method_rule],
"static_outlives_struct": static_ok,
"combined_announcement": [ann_msg, ann_longest],
}
expected_3 = {
"struct_content": "s.content = string_slice",
"method_elision": [True, "elided_to_self_lifetime"],
"static_outlives_struct": True,
"combined_announcement": ["Announcement! compare lengths", "ecmascript"],
}
cases.append(dict(
name="struct_elision_static_and_combined_fn",
summary="Verify Str<'a> holding &'static str, &self method elision rule 3, and longest_with_an_announcement",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
return cases
def main() -> None:
payload = {
"version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
"cases": run_cases(),
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 'a 超出 'b 被拒、双 &str 省略歧义与交集检验、&self 方法省略规则 3、'static 覆盖及 longest_with_an_announcement 输出。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:ffb7a0ecf6d89f6f6fa836ee1467f828b397c51905ac0affd9ca30e4ecd5633e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:c878b0e323872650420a1b22e3b5aad521026316f8d3614aa938854fe7be2a3d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 fn longer<'a>(s1: &'a str, s2: &'a str) -> &'a str 中,标注 'a 是否会延长较短参数的存活时间?返回引用的有效范围由什么决定?
展开参考解答
不会。生命周期注解从不改变值的实际存活期,它只描述约束关系:返回引用的有效范围受限于 s1 与 s2 两者生命周期的交集(即较短的那个作用域)。