【问题标题】:How can I use match on a pair of borrowed values without copying them?如何在不复制一对借用值的情况下使用匹配?
【发布时间】:2015-02-15 19:45:00
【问题描述】:

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

enum E {
    E1,
}

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

fn main() {}

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

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)]”,我的代码就会编译。

【问题讨论】:

    标签: rust


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 2019-09-25
      • 2014-07-10
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      相关资源
      最近更新 更多