【问题标题】:How to pattern match a Box to get a struct's attribute?如何对 Box 进行模式匹配以获取结构的属性?
【发布时间】:2018-09-19 04:29:19
【问题描述】:

我正在尝试访问枚举中盒装结构的属性,但我不知道如何与 std::boxed::Box 进行模式匹配

enum ArithExp {
    Sum {
        lhs: Box<ArithExp>,
        rhs: Box<ArithExp>,
    },
    Mul {
        lhs: Box<ArithExp>,
        rhs: Box<ArithExp>,
    },
    Num {
        value: f64,
    },
}

fn num(value: f64) -> std::boxed::Box<ArithExp> {
    Box::new(ArithExp::Num { value })
}

let mut number = num(1.0);
match number {
    ArithExp::Num { value } => println!("VALUE = {}", value),
}

我收到以下错误:

error[E0308]: mismatched types
  --> src/main.rs:22:9
   |
22 |         ArithExp::Num { value } => println!("VALUE = {}", value),
   |         ^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::boxed::Box`, found enum `main::ArithExp`
   |
   = note: expected type `std::boxed::Box<main::ArithExp>`
              found type `main::ArithExp`

访问属性的正确方法是什么?

【问题讨论】:

  • @ljedrz 我认为这有点不同。链接的问题专门与框本身的模式匹配有关。这更多的是匹配盒子的内容。

标签: rust


【解决方案1】:

您需要取消引用装箱的值,以便您可以访问框内的内容:

match *number {
    ArithExp::Num { value } => println!("VALUE = {}", value),
    _ => (),
}

playground

【讨论】:

    【解决方案2】:

    你不需要框enum:

    fn num(value: f64) -> ArithExp {
        ArithExp::Num { value }
    }
    

    编译器将给您的错误将是关于在match 臂中提供其余的enum 变体。您可以提供每一个,也可以提供一个_ arm ... 这意味着“其他任何东西”:

    let mut number = num(1.0);
    match number {
        ArithExp::Num { value } => println!("VALUE = {}", value),
        _ => (), // do nothing if its something else
    }
    

    Here it is running on the playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      相关资源
      最近更新 更多