Skip to content

Commit c621048

Browse files
vibhushitVibhushit Tyagi
andauthored
[rust/en] Update borrow example for NLL (#5459)
* [rust/en] Update borrow example for NLL * docs(rust): explain Non-Lexical Lifetimes in borrow examples --------- Co-authored-by: Vibhushit Tyagi <vibhushittyagi@Vibhushits-MacBook-Air.local>
1 parent 740f976 commit c621048

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

rust.md

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -321,28 +321,29 @@ fn main() {
321321
// Reference – an immutable pointer that refers to other data
322322
// When a reference is taken to a value, we say that the value has been ‘borrowed’.
323323
// While a value is borrowed immutably, it cannot be mutated or moved.
324-
// A borrow is active until the last use of the borrowing variable.
324+
// A borrow lasts from where it's created until its last use (Non-Lexical Lifetimes).
325325
let mut var = 4;
326326
var = 3;
327327
let ref_var: &i32 = &var;
328328

329329
println!("{}", var); // Unlike `mine`, `var` can still be used
330330
println!("{}", *ref_var);
331-
// var = 5; // this would not compile because `var` is borrowed
332-
// *ref_var = 6; // this would not either, because `ref_var` is an immutable reference
333-
ref_var; // no-op, but counts as a use and keeps the borrow active
334-
var = 2; // ref_var is no longer used after the line above, so the borrow has ended
331+
// *ref_var = 6; // this would not compile, because `ref_var` is an immutable reference
332+
333+
// After the last use of `ref_var` above, the borrow ends, so this reassignment is allowed.
334+
var = 2;
335335

336336
// Mutable reference
337337
// While a value is mutably borrowed, it cannot be accessed at all.
338338
let mut var2 = 4;
339339
let ref_var2: &mut i32 = &mut var2;
340340
*ref_var2 += 2; // '*' is used to point to the mutably borrowed var2
341341

342-
println!("{}", *ref_var2); // 6 , // var2 would not compile.
342+
println!("{}", *ref_var2); // 6
343343
// ref_var2 is of type &mut i32, so stores a reference to an i32, not the value.
344-
// var2 = 2; // this would not compile because `var2` is borrowed.
345-
ref_var2; // no-op, but counts as a use and keeps the borrow active until here
344+
345+
// After the last use of `ref_var2` above, the borrow ends, so this reassignment is allowed.
346+
var2 = 2;
346347
}
347348
```
348349

0 commit comments

Comments
 (0)