Skip to content

Commit

Permalink
Rollup merge of rust-lang#33384 - cramertj:E0506, r=arielb1
Browse files Browse the repository at this point in the history
Add detailed error explanation for E0506

Part of rust-lang#32777
  • Loading branch information
steveklabnik committed May 7, 2016
2 parents 6a92ac7 + 8facc97 commit 2926fe4
Showing 1 changed file with 84 additions and 1 deletion.
85 changes: 84 additions & 1 deletion src/librustc_borrowck/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,90 @@ fn foo(a: &mut i32) {
```
"##,

E0506: r##"
This error occurs when an attempt is made to assign to a borrowed value.
Example of erroneous code:
```compile_fail
struct FancyNum {
num: u8
}
fn main() {
let mut fancy_num = FancyNum { num: 5 };
let fancy_ref = &fancy_num;
fancy_num = FancyNum { num: 6 };
// error: cannot assign to `fancy_num` because it is borrowed
println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
}
```
Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
be assigned to a new value as it would invalidate the reference.
Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
```
struct FancyNum {
num: u8
}
fn main() {
let mut fancy_num = FancyNum { num: 5 };
let moved_num = fancy_num;
fancy_num = FancyNum { num: 6 };
println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
}
```
If the value has to be borrowed, try limiting the lifetime of the borrow using
a scoped block:
```
struct FancyNum {
num: u8
}
fn main() {
let mut fancy_num = FancyNum { num: 5 };
{
let fancy_ref = &fancy_num;
println!("Ref: {}", fancy_ref.num);
}
// Works because `fancy_ref` is no longer in scope
fancy_num = FancyNum { num: 6 };
println!("Num: {}", fancy_num.num);
}
```
Or by moving the reference into a function:
```
struct FancyNum {
num: u8
}
fn main() {
let mut fancy_num = FancyNum { num: 5 };
print_fancy_ref(&fancy_num);
// Works because function borrow has ended
fancy_num = FancyNum { num: 6 };
println!("Num: {}", fancy_num.num);
}
fn print_fancy_ref(fancy_ref: &FancyNum){
println!("Ref: {}", fancy_ref.num);
}
```
"##,

E0507: r##"
You tried to move out of a value which was borrowed. Erroneous code example:
Expand Down Expand Up @@ -516,7 +600,6 @@ register_diagnostics! {
E0503, // cannot use `..` because it was mutably borrowed
E0504, // cannot move `..` into closure because it is borrowed
E0505, // cannot move out of `..` because it is borrowed
E0506, // cannot assign to `..` because it is borrowed
E0508, // cannot move out of type `..`, a non-copy fixed-size array
E0509, // cannot move out of type `..`, which defines the `Drop` trait
E0524, // two closures require unique access to `..` at the same time
Expand Down

0 comments on commit 2926fe4

Please sign in to comment.