Skip to content

Commit c39e37a

Browse files
committed
Add explanation for E0503.
1 parent 763f923 commit c39e37a

File tree

1 file changed

+56
-1
lines changed

1 file changed

+56
-1
lines changed

src/librustc_borrowck/diagnostics.rs

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,62 @@ fn main() {
633633
```
634634
"##,
635635

636+
E0503: r##"
637+
A value was used after it was mutably borrowed.
638+
639+
Example of erroneous code:
640+
641+
```compile_fail
642+
fn main() {
643+
let mut value = 3;
644+
// Create a mutable borrow of `value`. This borrow
645+
// lives until the end of this function.
646+
let _borrow = &mut value;
647+
let _sum = value + 1; // error: cannot use `value` because
648+
// it was mutably borrowed
649+
}
650+
```
651+
652+
In this example, `value` is mutably borrowed by `borrow` and cannot be
653+
used to calculate `sum`. This is not possible because this would violate
654+
Rust's mutability rules.
655+
656+
You can fix this error by limiting the scope of the borrow:
657+
658+
```
659+
fn main() {
660+
let mut value = 3;
661+
// By creating a new block, you can limit the scope
662+
// of the reference.
663+
{
664+
let _borrow = &mut value; // Use `_borrow` inside this block.
665+
}
666+
// The block has ended and with it the borrow.
667+
// You can now use `value` again.
668+
let _sum = value + 1;
669+
}
670+
```
671+
672+
Or by cloning `value` before borrowing it:
673+
674+
```
675+
fn main() {
676+
let mut value = 3;
677+
// We clone `value`, creating a copy.
678+
let value_cloned = value.cloned();
679+
// The mutable borrow is a reference to `value` and
680+
// not to `value_cloned`...
681+
let _borrow = &mut value;
682+
// ... which means we can still use `value_cloned`,
683+
let _sum = value_cloned + 1;
684+
// even though the borrow only ends here.
685+
}
686+
```
687+
688+
You can find more information about borrowing in the rust-book:
689+
http://doc.rust-lang.org/stable/book/references-and-borrowing.html
690+
"##,
691+
636692
E0506: r##"
637693
This error occurs when an attempt is made to assign to a borrowed value.
638694
@@ -1011,7 +1067,6 @@ fn main() {
10111067
register_diagnostics! {
10121068
E0385, // {} in an aliasable location
10131069
E0388, // {} in a static location
1014-
E0503, // cannot use `..` because it was mutably borrowed
10151070
E0508, // cannot move out of type `..`, a non-copy fixed-size array
10161071
E0524, // two closures require unique access to `..` at the same time
10171072
}

0 commit comments

Comments
 (0)