How to end a borrow in a match or if let expression?

后端 未结 2 1440
轮回少年
轮回少年 2020-11-30 15:40

I am using a HashMap to store an enum. I\'d like to get a value from the HashMap and if the value is a specific enum variant, I\'d like to insert a

相关标签:
2条回答
  • 2020-11-30 16:10

    Here is Vladimir's solution using match:

    let mut result = match self.pages.get(&page) {
        Some(&Node::LeafNode(ref leaf_node)) => Some(leaf_node.clone()),
        _ => None,
    };
    if let Some(leaf_node) = result {
        // ...
        self.pages.insert(page_number, Node::LeafNode(leaf_node));
    };
    
    0 讨论(0)
  • 2020-11-30 16:17

    This is not possible at the moment. What you want is called non-lexical borrows and it is yet to be implemented in Rust. Meanwhile, you should use Entry API to work with maps - in most cases it should be sufficient. In this particular case I'm not sure if entries are applicable, but you can always do something like

    let mut result = None;
    if let Some(&Node::LeafNode(ref leaf_node)) = self.pages.get(&page) {
        let mut leaf_node = leaf_node.clone();
        // ...
        result = Some((leaf_page, leaf_node));
    }
    
    if let Some((leaf_page, leaf_node)) = result {
        self.pages.insert(leaf_page, leaf_node);
    }
    

    It is difficult to make the code above entirely correct given that you didn't provide definitions of Node and self.pages, but it should be approximately right. Naturally, it would work only if leaf_page and leaf_node do not contain references to self.pages or self, otherwise you won't be able to access self.pages.

    0 讨论(0)
提交回复
热议问题