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

前端 未结 3 785
太阳男子
太阳男子 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:09

    An Enum is a type with a constrained set of values.

    enum Rainbow {
        Red,
        Orange,
        Yellow,
        Green,
        Blue,
        Indigo,
        Violet
    }
    
    let color = Red;
    
    match color {
        Red => { handle Red case },
        // all the rest would go here
    }
    

    You can store data in the Enum if you need it.

    enum ParseData {
        Whitespace,
        Token(String),
        Number(i32),
    }
    
    fn parse(input: String) -> Result;
    

    A struct is a way to represent a thing.

    struct Window {
        title: String,
        position: Position,
        visible: boolean,
    }
    

    Now you can make new Window objects that represent a window on your screen.

提交回复
热议问题