1

In a match, I'm checking many conditions. If the check is successful, I want to save the item. Here's simplified code with only one condition:

struct Item {
    node: ItemKind,
}

struct Generics;

enum ItemKind {
    Impl(Generics),
}

fn main() {
    let item = Item { node: ItemKind::Impl(Generics) };
    let mut items = Vec::<Item>::new();
    match item {
        Item { node: ItemKind::Impl(ref generic), .. } => {
            // do some checks with generic
            // here we not need it anymore
            ::std::mem::forget(generic); // attempt to forget about generic doesn't help
            items.push(item);
        }
        _ => {}
    }
}

I got the error:

error[E0505]: cannot move out of `item` because it is borrowed
  --> src/main.rs:19:24
   |
15 |         Item { node: ItemKind::Impl(ref generic), .. } => {
   |                                     ----------- borrow of `item.node.0` occurs here
...
19 |             items.push(item);
   |                        ^^^^ move out of `item` occurs here

I do not need the generic reference on line items.push(item);, but I don't know how to tell the compiler that.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1244932
  • 7,352
  • 5
  • 46
  • 103
  • 2
    There are some other questions with the same problem. Quick answer: it's not possible right now due a limitation of the compiler, called lexical borrowing. Non-lexical borrow will probably be implemented soonish. You have to work around the issue, probably by using an ugly `bool` and call `push` after the `match`. – Lukas Kalbertodt Aug 12 '17 at 23:11
  • 2
    [One example of such a workaround](https://play.integer32.com/?gist=2e089100ad08d3bfb6439fead971d07c&version=stable). – Shepmaster Aug 13 '17 at 01:26

0 Answers0