When should we use a struct as opposed to an enum?

前端 未结 3 652
太阳男子
太阳男子 2021-02-14 08:29

Structs and enums are similar to each other.

When would it be better to use a struct as opposed to an enum (or vice-versa)? Can someone give a clear example where usin

3条回答
  •  借酒劲吻你
    2021-02-14 09:12

    Enums have multiple possibilities. Structs have only one possible "type" of thing they can be. Mathematically, we say a struct is a product type and an enum is a sum of products. If you only have one possibility, use a struct. For example, a point in space is always going to be three numbers. It's never going to be a string, or a function, or something else. So it should be a struct containing three numbers. On the other hand, if you're building a mathematical expression, it could be (for instance) a number or two expressions joined by an operator. It has multiple possibilities, so it should be an enum.

    In short, if a struct works, use a struct. Rust can optimize around it, and it's going to be clearer to anyone reading your code what the value is supposed to be treated as.

提交回复
热议问题