]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0503.md
Rollup merge of #92310 - ehuss:rustdoc-ice, r=estebank
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0503.md
1 A value was used after it was mutably borrowed.
2
3 Erroneous code example:
4
5 ```compile_fail,E0503
6 fn main() {
7     let mut value = 3;
8     // Create a mutable borrow of `value`.
9     let borrow = &mut value;
10     let _sum = value + 1; // error: cannot use `value` because
11                           //        it was mutably borrowed
12     println!("{}", borrow);
13 }
14 ```
15
16 In this example, `value` is mutably borrowed by `borrow` and cannot be
17 used to calculate `sum`. This is not possible because this would violate
18 Rust's mutability rules.
19
20 You can fix this error by finishing using the borrow before the next use of
21 the value:
22
23 ```
24 fn main() {
25     let mut value = 3;
26     let borrow = &mut value;
27     println!("{}", borrow);
28     // The block has ended and with it the borrow.
29     // You can now use `value` again.
30     let _sum = value + 1;
31 }
32 ```
33
34 Or by cloning `value` before borrowing it:
35
36 ```
37 fn main() {
38     let mut value = 3;
39     // We clone `value`, creating a copy.
40     let value_cloned = value.clone();
41     // The mutable borrow is a reference to `value` and
42     // not to `value_cloned`...
43     let borrow = &mut value;
44     // ... which means we can still use `value_cloned`,
45     let _sum = value_cloned + 1;
46     // even though the borrow only ends here.
47     println!("{}", borrow);
48 }
49 ```
50
51 For more information on Rust's ownership system, take a look at the
52 [References & Borrowing][references-and-borrowing] section of the Book.
53
54 [references-and-borrowing]: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html