Skip to content

Commit

Permalink
clean up E0506 explanation
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Apr 6, 2020
1 parent 1b521f5 commit 3a10bdc
Showing 1 changed file with 26 additions and 34 deletions.
60 changes: 26 additions & 34 deletions src/librustc_error_codes/error_codes/E0506.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
This error occurs when an attempt is made to assign to a borrowed value.
An attempt was made to assign to a borrowed value.

Erroneous code example:

Expand All @@ -7,14 +7,12 @@ 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
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);
}
println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
```

Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
Expand All @@ -27,13 +25,11 @@ struct FancyNum {
num: u8,
}
fn main() {
let mut fancy_num = FancyNum { num: 5 };
let moved_num = fancy_num;
fancy_num = FancyNum { num: 6 };
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);
}
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
Expand All @@ -44,18 +40,16 @@ struct FancyNum {
num: u8,
}
fn main() {
let mut fancy_num = FancyNum { num: 5 };
{
let fancy_ref = &fancy_num;
println!("Ref: {}", fancy_ref.num);
}
let mut fancy_num = FancyNum { num: 5 };
// Works because `fancy_ref` is no longer in scope
fancy_num = FancyNum { num: 6 };
println!("Num: {}", fancy_num.num);
{
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:
Expand All @@ -65,17 +59,15 @@ 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);
}
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);
```

0 comments on commit 3a10bdc

Please sign in to comment.