如何在不复制它们的情况下在一对借用值上使用匹配? [英] How can I use match on a pair of borrowed values without copying them?

查看:40
本文介绍了如何在不复制它们的情况下在一对借用值上使用匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将问题简化为以下代码:

I reduced my problem to the following code:

enum E {
    E1,
}

fn f(e1: &E, e2: &E) {
    match *e1 {
        E::E1 => (),
    }
    match (*e1, *e2) {
        (E::E1, E::E1) => (),
    }
}

fn main() {}

第一个匹配没问题,但第二个编译失败:

The first match is ok, but the second fails to compile:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:9:12
  |
9 |     match (*e1, *e2) {
  |            ^^^ cannot move out of borrowed content

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:9:17
  |
9 |     match (*e1, *e2) {
  |                 ^^^ cannot move out of borrowed content

这似乎是因为我正在构建一对借用的东西,而 Rust 试图将 e1e2 移动到其中.我发现如果我在枚举之前加上#[derive(Copy, Clone)]",我的代码就会编译.

It seems that this is because I'm constructing a pair of something borrowed and Rust tries to move e1 and e2 into it. I found out that if I put "#[derive(Copy, Clone)]" before my enum, my code compiles.

推荐答案

您可以通过从变量中删除取消引用运算符来匹配两个引用的元组:

You can match over a tuple of two references by removing the dereference operator from the variables:

enum E {
    E1,
}

fn f(e1: &E, e2: &E) {
    match *e1 {
        E::E1 => (),
    }
    match (e1, e2) {
        (&E::E1, &E::E1) => (),
    }
}

这篇关于如何在不复制它们的情况下在一对借用值上使用匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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