1 An attempt was made to assign to a borrowed value.
3 Erroneous code example:
10 let mut fancy_num = FancyNum { num: 5 };
11 let fancy_ref = &fancy_num;
12 fancy_num = FancyNum { num: 6 };
13 // error: cannot assign to `fancy_num` because it is borrowed
15 println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
18 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
19 be assigned to a new value as it would invalidate the reference.
21 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
28 let mut fancy_num = FancyNum { num: 5 };
29 let moved_num = fancy_num;
30 fancy_num = FancyNum { num: 6 };
32 println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
35 If the value has to be borrowed, try limiting the lifetime of the borrow using
43 let mut fancy_num = FancyNum { num: 5 };
46 let fancy_ref = &fancy_num;
47 println!("Ref: {}", fancy_ref.num);
50 // Works because `fancy_ref` is no longer in scope
51 fancy_num = FancyNum { num: 6 };
52 println!("Num: {}", fancy_num.num);
55 Or by moving the reference into a function:
62 fn print_fancy_ref(fancy_ref: &FancyNum){
63 println!("Ref: {}", fancy_ref.num);
66 let mut fancy_num = FancyNum { num: 5 };
68 print_fancy_ref(&fancy_num);
70 // Works because function borrow has ended
71 fancy_num = FancyNum { num: 6 };
72 println!("Num: {}", fancy_num.num);