Rust的规则:所有权、引用和生命周期

2026-03-18 · 约 3 分钟 · 标签: Rust , Programming Language , Memory Safety

Ownership is Rust’s most unique feature It enables Rust to make memory safety guarantees without needing a garbage collector

Rust uses a third approach: Memory is managed through a system of ownership with a set of rules that the compiler checks. If any of the rules are violated, the program won’t compile.

Ownership Rules

Each value in Rust has an owner. There can only be one owner at a time. When the owner goes out of scope, the value will be dropped.

The Rules of References

At any given time, you can have either one mutable reference or any number of immutable references. References must always be valid.

Lifetime elision rules(生命周期省略规则)

Lifetimes on function or method parameters are called input lifetimes, and lifetimes on return values are called output lifetimes.

The first rule is that the compiler assigns a lifetime parameter to each parameter that’s a reference. The second rule is that, if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters: fn foo<'a>(x: &'a i32) -> &'a i32. The third rule is that, if there are multiple input lifetime parameters, but one of them is &self or &mut self because this is a method, the lifetime of self is assigned to all output lifetime parameters.

评论
评论功能尚未配置:在 GitHub 仓库开启 Discussions,并按项目 README 里的步骤填好 src/consts.ts 即可启用(基于 Giscus,评论需要 GitHub 账号)。