Rust - Enum

eslerkang·2022년 3월 10일
0

Rust

목록 보기
6/10
post-thumbnail

Enum

Enum is similar with struct as they both help us to create our own type.
But the difference between them is 'Struct is AND' and 'Enum is OR'. Struct should have every properties we made, but at Enum, we just need one of them.
We can make enum like this

enum Season {
  Spring,
  Summer,
  Autumn,
  Winter
}

Each properties have index number. So at Season enum, Sprint is 0, Summer is 1, Autumn is 2, Winter is 3. Properties index number is +1 of its prior property. We can also manually assign the index number of properties

enum Star {
  BrownDwarf = 10,
  RedDwarf = 50,
  YellowStar = 100,
  RedGiant = 1000,
  DeadStar
}

at this example, as the index number is +1 of prior one, DeadStar is 1001.

If you want to use one of the properties of enum, we can use it by Star::BrownDwarf. And as it's a new type we made, Display cannot print this type, so we have to make is as i32... etc(like println!("{}", Star::BrownDwarf as i32)).

As getting the property of enum is quite long(Star::BrownDwarf), we can use use to enum.

enum Laugh {
	haha,
    hoho
}

fn main() {
	use Laugh::*;
    println!("{}", haha as i32);
}

This means we will use everything under the Laugh enum, and we can approach them just by writing the name(haha, hoho).

All examples above are about enum with index-like value. But we can also give them custom type and value.

enum Number {
  U32(u32),
  I32(i32),
}

This example means U32 includes u32 type, and I32 includes i32 type. And we can make i32, u32 into Number and treat them as a same type.

We can also use multiple values or struct to enum

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

Quit has no value, Move has named attributes like struct, Write has a String value, ChangeColor has three i32.

Like the example above, we can use widely the enum.

profile
Surfer surfing on the dynamic flow of the world

0개의 댓글