@@ -1545,20 +1545,22 @@ Erroneous code example:
1545
1545
```compile_fail,E0505
1546
1546
struct Value {}
1547
1547
1548
+ fn borrow(val: &Value) {}
1549
+
1548
1550
fn eat(val: Value) {}
1549
1551
1550
1552
fn main() {
1551
1553
let x = Value{};
1552
- {
1553
- let _ref_to_val: &Value = &x;
1554
- eat(x);
1555
- }
1554
+ let _ref_to_val: &Value = &x;
1555
+ eat(x);
1556
+ borrow(_ref_to_val);
1556
1557
}
1557
1558
```
1558
1559
1559
- Here, the function `eat` takes the ownership of `x`. However,
1560
- `x` cannot be moved because it was borrowed to `_ref_to_val`.
1561
- To fix that you can do few different things:
1560
+ Here, the function `eat` takes ownership of `x`. However,
1561
+ `x` cannot be moved because the borrow to `_ref_to_val`
1562
+ needs to last till the function `borrow`.
1563
+ To fix that you can do a few different things:
1562
1564
1563
1565
* Try to avoid moving the variable.
1564
1566
* Release borrow before move.
@@ -1569,14 +1571,15 @@ Examples:
1569
1571
```
1570
1572
struct Value {}
1571
1573
1574
+ fn borrow(val: &Value) {}
1575
+
1572
1576
fn eat(val: &Value) {}
1573
1577
1574
1578
fn main() {
1575
1579
let x = Value{};
1576
- {
1577
- let _ref_to_val: &Value = &x;
1578
- eat(&x); // pass by reference, if it's possible
1579
- }
1580
+ let _ref_to_val: &Value = &x;
1581
+ eat(&x); // pass by reference, if it's possible
1582
+ borrow(_ref_to_val);
1580
1583
}
1581
1584
```
1582
1585
@@ -1585,12 +1588,15 @@ Or:
1585
1588
```
1586
1589
struct Value {}
1587
1590
1591
+ fn borrow(val: &Value) {}
1592
+
1588
1593
fn eat(val: Value) {}
1589
1594
1590
1595
fn main() {
1591
1596
let x = Value{};
1592
1597
{
1593
1598
let _ref_to_val: &Value = &x;
1599
+ borrow(_ref_to_val);
1594
1600
}
1595
1601
eat(x); // release borrow and then move it.
1596
1602
}
@@ -1602,14 +1608,15 @@ Or:
1602
1608
#[derive(Clone, Copy)] // implement Copy trait
1603
1609
struct Value {}
1604
1610
1611
+ fn borrow(val: &Value) {}
1612
+
1605
1613
fn eat(val: Value) {}
1606
1614
1607
1615
fn main() {
1608
1616
let x = Value{};
1609
- {
1610
- let _ref_to_val: &Value = &x;
1611
- eat(x); // it will be copied here.
1612
- }
1617
+ let _ref_to_val: &Value = &x;
1618
+ eat(x); // it will be copied here.
1619
+ borrow(_ref_to_val);
1613
1620
}
1614
1621
```
1615
1622
0 commit comments