如何在Rust中使用带有枚举属性的struct?

时间:2018-09-19 01:39:19

标签: rust

我正在尝试创建一个结构,在该结构中,属性是一个枚举,但是当我实例化它时,我得到一个错误。

struct Sum {
    lhs: ArithExp,
    rhs: ArithExp,
}

enum ArithExp {
    Num,
    Sum,
}

struct Num {
    value: f64,
}

当我尝试使用Sum实例化Num时:

let sum = Sum {
    lhs: Num { value: 5.0 },
    rhs: Num { value: 2.0 },
};

我收到以下错误:

error[E0308]: mismatched types
  --> src/main.rs:17:14
   |
17 |         lhs: Num { value: 5.0 },
   |              ^^^^^^^^^^^^^^^^^^ expected enum `ArithExp`, found struct `Num`
   |
   = note: expected type `ArithExp`
              found type `Num`

error[E0308]: mismatched types
  --> src/main.rs:18:14
   |
18 |         rhs: Num { value: 2.0 },
   |              ^^^^^^^^^^^^^^^^^^ expected enum `ArithExp`, found struct `Num`
   |
   = note: expected type `ArithExp`
              found type `Num`

正确的方法是什么?

我发现这可行:

let x = Sum { lhs: 5.0, rhs: 2.0 };
match x {
    ArithExp => println!("Sum is an ArithExp"),
}

0 个答案:

没有答案
相关问题