본문 바로가기

Rust

(Rust) - enum vs struct

반응형

🍳머리말

Rust에서는 enum과 struct가 비슷하게 생겼습니다. 이들 특징과 차이를 알아봅시다 


📕 Enum

📔 설명 부연 제목

algibraic data type을 위해 존재합니다. 아래처럼 다양한 형태로 사용 가능합니다. 덕분에 값이 무슨 의미를 가지는지 알 수 있습니다.

📑 선언

enum SimpleEnum {
    FirstVariant,
    SecondVariant,
    ThirdVariant,
}

enum Location {
    Unknown,
    Anonymous,
    Known(Coord),
}

enum ComplexEnum {
    Nothing,
    Something(u32),
    LotsOfThings {
        usual_struct_stuff: bool,
        blah: String,
    }
}

enum EmptyEnum { }

📑 instance 생성

::로 같은 종류의 enum내 variant 구분이 가능하며 다음처럼 생성합니다.

let first = SimpleEnum::FirstVariant

📑 접근

이렇게 함수에 enum을 넘겨줄 수 있습니다. 

fn route(simple_enum: SimpleEnum) {}

상위 type의 인자를 넘겨줄 수 있으므로 이에 속한 다양한 variant들 또한 마찬가지로 함수 호출시 인자로 넘겨 줄 수 있습니다.

route(SimpleEnum::FirstVariant)
route(SimpleEnum::SecondVariant)
route(SimpleEnum::ThirdVariant)

📕 Struct

📔 설명

tuple과 비슷하지만 객체 생성시 인자의 순서를 고려하지 않아도 되는 좀 더 유연한 구조입니다.

 📑 선언

선언시 value로 type을 명시해줍니다.

struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

📑 instance 생성

생성시 value로 명확한 type명시가 필요합니다.

fn main() {
    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };
}

📑 접근

".(dot)" 을 사용해 instance의 내부인 field들에 접근할 수 있습니다.

fn main() {
    let mut user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };

    user1.email = String::from("anotheremail@example.com");
}

📕 Enum vs Struct

📔 설명

얼핏보면 enum과 struct는 비슷하다는 느낌입니다. 하지만 분명 생김새 말고 차이가 있을 겁니다.

📑 예시

📘 enum

 

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

 

📘 struct

 

struct Message {
    Quit: bool,
    Move: Option<(i32, i32)>,
    Write: Option<String>,
    ChangeColor: Option<(i32, i32, i32)>,
}

 

📑 차이 1

Enum은 variant 중 하나만 선택하게 되는 Or구조입니다. Struct가 동일한 동작을 원하면 내부 field를 private으로 바꿔야 합니다.

때문에 Compiler입장에서는 variant경우 같은 memory에 저장할 수 있습니다. 한 공간에는 하나의 variant만 선택됨이 보장되기 때문입니다. 예를 들어 Move, ChangeColor는 동시에 같은 공간에 저장할 수 있습니다.

 

Struct는 field가 몇 개 사용되는지 compiler가 모르기 때문에 각 field에 별도 공간을 할당해야 합니다.

📑 차이 2

주관적인 생각이지만

Enum은 struct보다 편하게 match문을 적용할 수 있습니다.

 

enum은  바로 접근 가능합니다.

struct는 match구문을 사용하려면 모든 field 들을 고려해야하며 복잡합니다.

 

📘 enum match 구문 예시

 

#![allow(unused)]

fn main() {
    enum Message {
        Quit,
        Move { x: i32, y: i32 },
        Write(String),
    }
   
    let a = Message::Move{x: 10, y: 5};
    
    match a {
        Message::Quit => println!("bye~"),
        Message::Move { x, y } => println!("x is {}, y is {}", x, y),
        Message::Write(s) => println!("write~ {}", s)
    }
}

📘 struct match 구문 예시

 

#![allow(unused)]
fn main() {
    struct Message {
        Quit: bool,
        Move: Option<(i32, i32)>,
        Write: Option<String>,
    }
    
    let a = Message{
        Quit: true,
        Move: Some((1,2)),
        Write: Some("s".to_owned())
    };
    
    match a {
        // Message { Quit: true, .. } => println!("bye~"),
        Message { Quit: true, Move: Some((x,y)), .. } => println!("bye~ and x is {}, y is {}", x, y),
        Message { Quit: true, Move: None, .. } => println!("bye~ and no move"),
        Message { Quit: false, .. } => println!("not bye~"),
    }
}

 


📕 결론

📑 용도에 맞게 사용해 봅시다


📕참조

https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html

 

Defining an Enum - The Rust Programming Language

Where structs give you a way of grouping together related fields and data, like a Rectangle with its width and height, enums give you a way of saying a value is one of a possible set of values. For example, we may want to say that Rectangle is one of a set

doc.rust-lang.org

https://doc.rust-lang.org/rust-by-example/primitives/tuples.html

 

Tuples - Rust By Example

A tuple is a collection of values of different types. Tuples are constructed using parentheses (), and each tuple itself is a value with type signature (T1, T2, ...), where T1, T2 are the types of its members. Functions can use tuples to return multiple va

doc.rust-lang.org

https://doc.rust-lang.org/book/ch05-01-defining-structs.html

 

Defining and Instantiating Structs - The Rust Programming Language

Structs are similar to tuples, discussed in “The Tuple Type” section, in that both hold multiple related values. Like tuples, the pieces of a struct can be different types. Unlike with tuples, in a struct you’ll name each piece of data so it’s clea

doc.rust-lang.org

https://www.reddit.com/r/rust/comments/93valt/differences_between_struct_and_enum/

 

Differences between struct and enum

I'm trying to wrap my head around the differences. I've reread chapters 5 and 6 a few times but it's just not clicking for me. For example, why...

www.reddit.com


*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.

'Rust' 카테고리의 다른 글

(Rust) - 입출력  (0) 2022.08.07