如何在匹配或 if let 表达式中结束借用? [英] How to end a borrow in a match or if let expression?

查看:30
本文介绍了如何在匹配或 if let 表达式中结束借用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 HashMap 来存储枚举.我想从 HashMap 获取一个值,如果该值是特定的枚举变体,我想在 HashMap 中插入该值的修改副本>.

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 modified copy of the value back in the HashMap.

我想出的代码是这样的:

The code I came up with looks like this:

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

这不会编译,因为 self.pages 的借用会持续到 if let-block 和 self.pages.insert 的结尾> 是可变借用.

This does not compile because the borrow of self.pages lasts until the end of the if let-block and self.pages.insert is a mutable borrow.

我试图用值的副本来隐藏 HashMap 的值,但这并没有结束借用.通常我会使用 {} 块来限制借用,但这在 matchif let 中似乎是不可能的.

I have tried to shadow the value of the HashMap with a copy of the value, but this does not end the borrow. Usually I would use a {} block to limit the borrow, but this seems to be not possible in match or if let.

结束借用以便获得新的可变借用的惯用方法是什么?

What is the idiomatic way to end a borrow so that I can get a new mutable borrow?

推荐答案

目前无法实现.你想要的是非词法借用,它尚未在锈.同时,你应该使用 Entry 用于处理地图的 API - 在大多数情况下应该足够了.在这种特殊情况下,我不确定条目是否适用,但您始终可以执行类似的操作

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);
}

鉴于您没有提供 Nodeself.pages 的定义,很难使上面的代码完全正确,但它应该大致正确.自然,它只有在 leaf_pageleaf_node 不包含对 self.pagesself 的引用时才有效,否则您将无法访问 self.pages.

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.

这篇关于如何在匹配或 if let 表达式中结束借用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆