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