How to pattern match a Box to get a struct's attribute?

南楼画角 提交于 2020-12-15 06:49:04

问题


I'm trying to access an attribute of a boxed struct inside an enum but I can't figure out how to pattern-match with 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),
}

I get the following error:

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`

What is the correct way of accessing the attribute?


回答1:


You need to dereference the boxed value so that you can access what's inside the box:

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

playground




回答2:


You don't need to box the enum:

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

The error the compiler will give you will be about providing the rest of the enum variants in the match arms. You can either provide each one, or provide an _ arm ... which means "anything else":

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



来源:https://stackoverflow.com/questions/52398060/how-to-pattern-match-a-box-to-get-a-structs-attribute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!