Skip to content

Commit f841f06

Browse files
committed
Improve message for rustc --explain E0507
E0507 can occur when you try to move out of a member of a mutably borrowed struct, in which case `mem::replace` can help. Mentioning that here hopefully saves future users a trip to Google.
1 parent b8b18aa commit f841f06

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/librustc_borrowck/diagnostics.rs

+27
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,33 @@ fn main() {
377377
}
378378
```
379379
380+
Moving out of a member of a mutably borrowed struct is fine if you put something
381+
back. `mem::replace` can be used for that:
382+
383+
```
384+
struct TheDarkKnight;
385+
386+
impl TheDarkKnight {
387+
fn nothing_is_true(self) {}
388+
}
389+
390+
struct Batcave {
391+
knight: TheDarkKnight
392+
}
393+
394+
fn main() {
395+
use std::mem;
396+
397+
let mut cave = Batcave {
398+
knight: TheDarkKnight
399+
};
400+
let borrowed = &mut cave;
401+
402+
borrowed.knight.nothing_is_true(); // E0507
403+
mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
404+
}
405+
```
406+
380407
You can find more information about borrowing in the rust-book:
381408
http://doc.rust-lang.org/stable/book/references-and-borrowing.html
382409
"##,

0 commit comments

Comments
 (0)