Published on

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

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.

THE END