File: two-phase-allow-access-during-reservation.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (38 lines) | stat: -rw-r--r-- 1,582 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//@ revisions: nll_target

// The following revisions are disabled due to missing support for two_phase_beyond_autoref
//@ unused-revision-names: nll_beyond
//@[nll_beyond] compile-flags: -Z two_phase_beyond_autoref

// This is the second counter-example from Niko's blog post
// smallcultfollowing.com/babysteps/blog/2017/03/01/nested-method-calls-via-two-phase-borrowing/
//
// It is "artificial". It is meant to illustrate directly that we
// should allow an aliasing access during reservation, but *not* while
// the mutable borrow is active.
//
// The convention for the listed revisions: "lxl" means lexical
// lifetimes (which can be easier to reason about). "nll" means
// non-lexical lifetimes. "nll_target" means the initial conservative
// two-phase borrows that only applies to autoref-introduced borrows.
// "nll_beyond" means the generalization of two-phase borrows to all
// `&mut`-borrows (doing so makes it easier to write code for specific
// corner cases).

fn main() {
    /*0*/ let mut i = 0;

    /*1*/ let p = &mut i; // (reservation of `i` starts here)

    /*2*/ let j = i;      // OK: `i` is only reserved here
                          //[nll_target]~^  ERROR cannot use `i` because it was mutably borrowed [E0503]

    /*3*/ *p += 1;        // (mutable borrow of `i` starts here, since `p` is used)

    /*4*/ let k = i;      //[nll_beyond]~  ERROR cannot use `i` because it was mutably borrowed [E0503]
                          //[nll_target]~^ ERROR cannot use `i` because it was mutably borrowed [E0503]

    /*5*/ *p += 1;

    let _ = (j, k, p);
}