]> git.proxmox.com Git - rustc.git/blame - src/librustc_error_codes/error_codes/E0505.md
New upstream version 1.47.0+dfsg1
[rustc.git] / src / librustc_error_codes / error_codes / E0505.md
CommitLineData
60c5eb7d
XL
1A value was moved out while it was still borrowed.
2
3Erroneous code example:
4
5```compile_fail,E0505
6struct Value {}
7
8fn borrow(val: &Value) {}
9
10fn eat(val: Value) {}
11
12fn main() {
13 let x = Value{};
14 let _ref_to_val: &Value = &x;
15 eat(x);
16 borrow(_ref_to_val);
17}
18```
19
20Here, the function `eat` takes ownership of `x`. However,
21`x` cannot be moved because the borrow to `_ref_to_val`
22needs to last till the function `borrow`.
23To 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
29Examples:
30
31```
32struct Value {}
33
34fn borrow(val: &Value) {}
35
36fn eat(val: &Value) {}
37
38fn 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
47Or:
48
49```
50struct Value {}
51
52fn borrow(val: &Value) {}
53
54fn eat(val: Value) {}
55
56fn 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
66Or:
67
68```
69#[derive(Clone, Copy)] // implement Copy trait
70struct Value {}
71
72fn borrow(val: &Value) {}
73
74fn eat(val: Value) {}
75
76fn 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
74b04a01
XL
84For more information on Rust's ownership system, take a look at the
85[References & Borrowing][references-and-borrowing] section of the Book.
86
87[references-and-borrowing]: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html