From 3a10bdcfb69b762c0520c57a8b7bd5cccf2e2875 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 6 Apr 2020 14:20:01 +0200 Subject: [PATCH] clean up E0506 explanation --- src/librustc_error_codes/error_codes/E0506.md | 60 ++++++++----------- 1 file changed, 26 insertions(+), 34 deletions(-) diff --git a/src/librustc_error_codes/error_codes/E0506.md b/src/librustc_error_codes/error_codes/E0506.md index 9b8e316487203..c312a0460e3a1 100644 --- a/src/librustc_error_codes/error_codes/E0506.md +++ b/src/librustc_error_codes/error_codes/E0506.md @@ -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: @@ -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 @@ -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 @@ -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: @@ -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); ```