1A value was moved out while it was still borrowed.23Erroneous code example:45```compile_fail,E05056struct Value {}78fn borrow(val: &Value) {}910fn eat(val: Value) {}1112fn main() {13 let x = Value{};14 let _ref_to_val: &Value = &x;15 eat(x);16 borrow(_ref_to_val);17}18```1920Here, 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:2425* Try to avoid moving the variable.26* Release borrow before move.27* Implement the `Copy` trait on the type.2829Examples:3031```32struct Value {}3334fn borrow(val: &Value) {}3536fn eat(val: &Value) {}3738fn main() {39 let x = Value{};4041 let ref_to_val: &Value = &x;42 eat(&x); // pass by reference, if it's possible43 borrow(ref_to_val);44}45```4647Or:4849```50struct Value {}5152fn borrow(val: &Value) {}5354fn eat(val: Value) {}5556fn main() {57 let x = Value{};5859 let ref_to_val: &Value = &x;60 borrow(ref_to_val);61 // ref_to_val is no longer used.62 eat(x);63}64```6566Or:6768```69#[derive(Clone, Copy)] // implement Copy trait70struct Value {}7172fn borrow(val: &Value) {}7374fn eat(val: Value) {}7576fn 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```8384For more information on Rust's ownership system, take a look at the85[References & Borrowing][references-and-borrowing] section of the Book.8687[references-and-borrowing]: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
Findings
✓ No findings reported for this file.