μ΄κ±°ν
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); } }