[Rust] Enums

고승우·2024년 7월 24일
0

Rust

목록 보기
14/16
post-thumbnail

In Rust, an enum is a type that can represent one of several distinct variants, each of which can hold different data. In memory, values of C-style enums are stored as integers. Occasionally it’s useful to
tell Rust which integers to use:

enum HttpStatus { Ok = 200,
    NotModified = 304,
    NotFound = 404,
}

Rust has three kinds of enum variant.
1. Variants with no data: correspond to unit-like structs
2. Tuple variants: look like tuple struct
3. Struct variants: have curly braces and named fields

enum RelationshipStatus {
    Single,
    InARelationship,
    ItsComplicated(Option<String>),
    ItsExtremelyComplicated {
        car: DifferentialEquation,
        cdr: EarlyModernistPoem,
    },
}

Enums in Memory

enums with data are stored as a small integer tag, plus enough memory to hold all the fields of the largest variant.

enum RoughTime {
    InThePast(TimeUnit, u32),
    JustNow,
    InTheFuture(TimeUnit, u32),
}

Generic Enums

Enums can be generic. Two examples from the standard library are among the most- used data types in the language:

enum Option<T> {
    None,
    Some(T),
}
enum Result<T, E> {
    Ok(T),
    Err(E),
}

Smart pointer with Option

Since none of those pointer types is allowed to be zero, Rust can represent Option<Box<i32>>, say, as a single machine word: 0 for None and nonzero for Some pointer.

Conclusion

Enums are ideal for representing values that can be one of several distinct types or possibly none, offering advantages over class hierarchies: they are faster, safer, require less code, and are easier to document. However, enums lack flexibility, as they can't be extended with new variants by end users. To add flexibility, we can use traits to define shared behaviors across different types.

profile
٩( ᐛ )و 

0개의 댓글