์ด๊ฑฐํ
enum
ํค์๋๋ ๋ช๊ฐ์ง ๋ณํ(variant)์ผ๋ก ํํ๋๋ ์ด๊ฑฐํ ํ์
์ ์์ฑํฉ๋๋ค:
#[derive(Debug)] enum Direction { Left, Right, } #[derive(Debug)] enum PlayerMove { Pass, // ๋จ์ ๋ณํ Run(Direction), // ํํ ๋ณํ Teleport { x: u32, y: u32 }, // ๊ตฌ์กฐ์ฒด ๋ณํ } fn main() { let m: PlayerMove = PlayerMove::Run(Direction::Left); println!("์ด๋ฒ ์ฐจ๋ก: {:?}", m); }
ํค ํฌ์ธํธ:
- Enumerations allow you to collect a set of values under one type.
Direction
์ ๋ณํ์ ๊ฐ์ง๋ ์ด๊ฑฐํ ํ์ ์ ๋๋ค. ์ฌ๊ธฐ์๋Direction::Left
์Direction::Right
์ ๋ ๊ฐ์ด ํฌํจ๋ฉ๋๋ค.PlayerMove
is a type with three variants. In addition to the payloads, Rust will store a discriminant so that it knows at runtime which variant is in aPlayerMove
value.- This might be a good time to compare structs and enums:
- In both, you can have a simple version without fields (unit struct) or one with different types of fields (variant payloads).
- You could even implement the different variants of an enum with separate structs but then they wouldnโt be the same type as they would if they were all defined in an enum.
- Rust๋ ํ๋ณ์์ ์ ์ฅํ๋ ๋ฐ ์ต์ํ์ ๊ณต๊ฐ์ ์ฌ์ฉํฉ๋๋ค.
-
ํ์ํ ๊ฒฝ์ฐ ํ์ํ ๊ฐ์ฅ ์์ ํฌ๊ธฐ์ ์ ์๋ฅผ ์ ์ฅํฉ๋๋ค.
-
ํ์ฉ๋ ๋ณํ ๊ฐ์ด ๋ชจ๋ ๋นํธ ํจํด์ ํฌํจํ์ง ์๋ ๊ฒฝ์ฐ ์๋ชป๋ ๋นํธ ํจํด์ ์ฌ์ฉํ์ฌ ํ๋ณ์์ ์ธ์ฝ๋ฉํฉ๋๋ค(โํ์ ์ต์ ํโ). ์๋ฅผ ๋ค์ด
Option<&u8>
์ ์ ์๋ฅผ ๊ฐ๋ฆฌํค๋ ํฌ์ธํฐ๋None
๋ณํ์ ๊ฒฝ์ฐNULL
์ ์ ์ฅํฉ๋๋ค. -
C์์ ์ฐ๋์ ์ํด ์๋ณ์ ๊ฐ์ ์ง์ ์ง์ ํ ์๋ ์์ต๋๋ค:
#[repr(u32)] enum Bar { A, // 0 B = 10000, C, // 10001 } fn main() { println!("A: {}", Bar::A as u32); println!("B: {}", Bar::B as u32); println!("C: {}", Bar::C as u32); }
repr
์์ฑ์ด ์๋ค๋ฉด 10001์ด 2 ๋ฐ์ดํธ๋ก ํํ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์ ์๋ณ์์ ํ์ ํฌ๊ธฐ๋ 2 ๋ฐ์ดํธ๊ฐ ๋ฉ๋๋ค.
-
๋ ์ดํด๋ณด๊ธฐ
Rust์๋ enum์ด ๋ ์ ์ ๊ณต๊ฐ์ ์ฐจ์งํ๋๋ก ํ๋ ๋ฐ ์ฌ์ฉํ ์ ์๋ ์ฌ๋ฌ ์ต์ ํ๊ฐ ์์ต๋๋ค.
-
๋ํฌ์ธํฐ ์ต์ ํ: ์ด๋ค ํ์ ๋ค์ ๋ํด์ ๋ฌ์คํธ๋
size_of::<T>()
๊ฐsize_of::<Option<T>>()
์ ๊ฐ์ ๊ฒ์ ๋ณด์ฅํฉ๋๋ค.์ค์ ๋ก ๋ํฌ์ธํฐ ์ต์ ํ๊ฐ ์ ์ฉ๋ ๊ฒ์ ํ์ธํ๊ณ ์ถ๋ค๋ฉด ์๋์ ์์ ์ฝ๋๋ฅผ ์ฌ์ฉํ์ธ์. ์ฃผ์ํ ์ ์, ์ฌ๊ธฐ์์ ๋ณด์ฌ์ฃผ๋ ๋นํธ ํจํด์ด ์ปดํ์ผ๋ฌ๊ฐ ๋ณด์ฅํด ์ฃผ๋ ๊ฒ์ ์๋๋ผ๋ ์ ์ ๋๋ค. ์ฌ๊ธฐ์ ์์กดํ๋ ๊ฒ์ ์์ ํ unsafeํฉ๋๋ค.
use std::mem::transmute; macro_rules! dbg_bits { ($e:expr, $bit_type:ty) => { println!("- {}: {:#x}", stringify!($e), transmute::<_, $bit_type>($e)); }; } fn main() { unsafe { println!("bool:"); dbg_bits!(false, u8); dbg_bits!(true, u8); println!("Option<bool>:"); dbg_bits!(None::<bool>, u8); dbg_bits!(Some(false), u8); dbg_bits!(Some(true), u8); println!("Option<Option<bool>>:"); dbg_bits!(Some(Some(false)), u8); dbg_bits!(Some(Some(true)), u8); dbg_bits!(Some(None::<bool>), u8); dbg_bits!(None::<Option<bool>>, u8); println!("Option<&i32>:"); dbg_bits!(None::<&i32>, usize); dbg_bits!(Some(&0i32), usize); } }