]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_error_codes/src/error_codes/E0713.md
New upstream version 1.68.2+dfsg1
[rustc.git] / compiler / rustc_error_codes / src / error_codes / E0713.md
1 This error occurs when an attempt is made to borrow state past the end of the
2 lifetime of a type that implements the `Drop` trait.
3
4 Erroneous code example:
5
6 ```compile_fail,E0713
7 pub struct S<'a> { data: &'a mut String }
8
9 impl<'a> Drop for S<'a> {
10 fn drop(&mut self) { self.data.push_str("being dropped"); }
11 }
12
13 fn demo<'a>(s: S<'a>) -> &'a mut String { let p = &mut *s.data; p }
14 ```
15
16 Here, `demo` tries to borrow the string data held within its
17 argument `s` and then return that borrow. However, `S` is
18 declared as implementing `Drop`.
19
20 Structs implementing the `Drop` trait have an implicit destructor that
21 gets called when they go out of scope. This destructor gets exclusive
22 access to the fields of the struct when it runs.
23
24 This means that when `s` reaches the end of `demo`, its destructor
25 gets exclusive access to its `&mut`-borrowed string data. allowing
26 another borrow of that string data (`p`), to exist across the drop of
27 `s` would be a violation of the principle that `&mut`-borrows have
28 exclusive, unaliased access to their referenced data.
29
30 This error can be fixed by changing `demo` so that the destructor does
31 not run while the string-data is borrowed; for example by taking `S`
32 by reference:
33
34 ```
35 pub struct S<'a> { data: &'a mut String }
36
37 impl<'a> Drop for S<'a> {
38 fn drop(&mut self) { self.data.push_str("being dropped"); }
39 }
40
41 fn demo<'a>(s: &'a mut S<'a>) -> &'a mut String { let p = &mut *(*s).data; p }
42 ```
43
44 Note that this approach needs a reference to S with lifetime `'a`.
45 Nothing shorter than `'a` will suffice: a shorter lifetime would imply
46 that after `demo` finishes executing, something else (such as the
47 destructor!) could access `s.data` after the end of that shorter
48 lifetime, which would again violate the `&mut`-borrow's exclusive
49 access.