
上QQ阅读APP看书,第一时间看更新
Enumerations
While a structure allows us to get multiple values under the same variable, enumerations allow us to choose one value from different types of values.
For example, let's write a type representing an expression:
enum Expr { Null, Add(i32, i32), Sub(i32, i32), Mul(i32, i32), Div { pidend: i32, pisor: i32 }, Val(i32), } let quotient = Expr::Div { pidend: 10, pisor: 2 }; let sum = Expr::Add(40, 2);
The Null variant does not have a value associated with it, Val has one associated value, and Add has two. Div also has two associated values, but they are named, similar to how we define a structure.