Skip to content

Commit e06fbe1

Browse files
committed
Add explanation for E0503
1 parent 81cd752 commit e06fbe1

File tree

1 file changed

+56
-1
lines changed

1 file changed

+56
-1
lines changed

src/librustc_borrowck/diagnostics.rs

+56-1
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,62 @@ For more information on the rust ownership system, take a look at
529529
https://doc.rust-lang.org/stable/book/references-and-borrowing.html.
530530
"##,
531531

532+
E0503: r##"
533+
A value was used after it was mutably borrowed.
534+
535+
Example of erroneous code:
536+
537+
```compile_fail
538+
fn main() {
539+
let mut value = 3;
540+
// Create a mutable borrow of `value`. This borrow
541+
// lives until the end of this function.
542+
let _borrow = &mut value;
543+
let _sum = value + 1; // error: cannot use `value` because
544+
// it was mutably borrowed
545+
}
546+
```
547+
548+
In this example, `value` is mutably borrowed by `borrow` and cannot be
549+
used to calculate `sum`. This is not possible because this would violate
550+
Rust's mutability rules.
551+
552+
You can fix this error by limiting the scope of the borrow:
553+
554+
```
555+
fn main() {
556+
let mut value = 3;
557+
// By creating a new block, you can limit the scope
558+
// of the reference.
559+
{
560+
let _borrow = &mut value; // Use `_borrow` inside this block.
561+
}
562+
// The block has ended and with it the borrow.
563+
// You can now use `value` again.
564+
let _sum = value + 1;
565+
}
566+
```
567+
568+
Or by cloning `value` before borrowing it:
569+
570+
```
571+
fn main() {
572+
let mut value = 3;
573+
// We clone `value`, creating a copy.
574+
let value_cloned = value.clone();
575+
// The mutable borrow is a reference to `value` and
576+
// not to `value_cloned`...
577+
let _borrow = &mut value;
578+
// ... which means we can still use `value_cloned`,
579+
let _sum = value_cloned + 1;
580+
// even though the borrow only ends here.
581+
}
582+
```
583+
584+
You can find more information about borrowing in the rust-book:
585+
http://doc.rust-lang.org/stable/book/references-and-borrowing.html
586+
"##,
587+
532588
E0504: r##"
533589
This error occurs when an attempt is made to move a borrowed variable into a
534590
closure.
@@ -1055,6 +1111,5 @@ fn main() {
10551111
register_diagnostics! {
10561112
E0385, // {} in an aliasable location
10571113
E0388, // {} in a static location
1058-
E0503, // cannot use `..` because it was mutably borrowed
10591114
E0524, // two closures require unique access to `..` at the same time
10601115
}

0 commit comments

Comments
 (0)