今日已更新 212 条资讯 | 累计 24871 条内容
关于我们

[Advanced Rust] 1.11. Lifetimes (Advanced) Pt.1 - Review, Borrow Checker, Generic Lifetimes

SomeB1oody 2026年07月28日 08:28 0 次阅读 来源:Dev.to

1.11.1. Review In the beginner tutorial, we mentioned that every reference in Rust has a lifetime. A lifetime is the scope in which the reference remains valid, and in most cases it is implicit and inferred by the compiler. When you take a reference to a variable, the lifetime begins. When the variable is moved or goes out of scope, the lifetime ends. In other words, for a reference, a lifetime is the name of the code region in which it must remain valid. Lifetimes usually overlap with scopes, but not always. 1.11.2. Borrow Checker Whenever a reference with some lifetime 'a is used, the borrow checker checks whether 'a is still alive. The process is: Trace the path back to where 'a began — that is, where the reference was obtained From there, check whether there are conflicts along that path Ensure that the reference points to a value that can be accessed safely This example uses the rand crate. Add the following dependency to Cargo.toml : [dependencies] rand = "0.8" Consider this example: use rand :: random ; fn main () { let mut x = Box :: new ( 42 ); let r = & x ; if random :: < f32 > () > 0.5 { * x = 84 ; } else { println! ( "{}" , r ); } } x is of type Box<i32> Declaring r as a reference to x means the reference’s lifetime begins on that line (line 5) On line 7, the value of x is modified through dereferencing. That requires a mutable reference to x . At this point, the borrow checker looks for a mutable reference to x and checks whether its use conflicts with anything else. In this example there is no conflict, so the code is valid You may ask: line 7 is inside the scope of r . Since *x needs a mutable reference to x , shouldn’t having both the immutable reference r and the mutable reference *x in the same scope violate the borrowing rules and produce an error? In fact, Rust is smart enough to know that if the if branch is taken, the else branch cannot be taken. r is never used in the if branch at all, so using the mutable reference *x in the if branch is fine

本文内容来源于互联网,版权归原作者所有
查看原文