]> git.proxmox.com Git - rustc.git/blob - src/librustc_error_codes/error_codes/E0505.md
New upstream version 1.41.1+dfsg1
[rustc.git] / src / librustc_error_codes / error_codes / E0505.md
1 A value was moved out while it was still borrowed.
2
3 Erroneous code example:
4
5 ```compile_fail,E0505
6 struct Value {}
7
8 fn borrow(val: &Value) {}
9
10 fn eat(val: Value) {}
11
12 fn main() {
13 let x = Value{};
14 let _ref_to_val: &Value = &x;
15 eat(x);
16 borrow(_ref_to_val);
17 }
18 ```
19
20 Here, the function `eat` takes ownership of `x`. However,
21 `x` cannot be moved because the borrow to `_ref_to_val`
22 needs to last till the function `borrow`.
23 To fix that you can do a few different things:
24
25 * Try to avoid moving the variable.
26 * Release borrow before move.
27 * Implement the `Copy` trait on the type.
28
29 Examples:
30
31 ```
32 struct Value {}
33
34 fn borrow(val: &Value) {}
35
36 fn eat(val: &Value) {}
37
38 fn main() {
39 let x = Value{};
40
41 let ref_to_val: &Value = &x;
42 eat(&x); // pass by reference, if it's possible
43 borrow(ref_to_val);
44 }
45 ```
46
47 Or:
48
49 ```
50 struct Value {}
51
52 fn borrow(val: &Value) {}
53
54 fn eat(val: Value) {}
55
56 fn main() {
57 let x = Value{};
58
59 let ref_to_val: &Value = &x;
60 borrow(ref_to_val);
61 // ref_to_val is no longer used.
62 eat(x);
63 }
64 ```
65
66 Or:
67
68 ```
69 #[derive(Clone, Copy)] // implement Copy trait
70 struct Value {}
71
72 fn borrow(val: &Value) {}
73
74 fn eat(val: Value) {}
75
76 fn main() {
77 let x = Value{};
78 let ref_to_val: &Value = &x;
79 eat(x); // it will be copied here.
80 borrow(ref_to_val);
81 }
82 ```
83
84 You can find more information about borrowing in the rust-book:
85 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html