Penflip

Penflip - Write better with others

  • Loading...
  • Discover Projects
  • Help
  • Signup
  • Login
  • Welcome back!
    No account? Signup Close
    Ready to write better?
    Have an account? Login Close

sarojaba · Rust Doc Korean

Make Changes
46

5.13. 열거형 (Enums) - 0%

An enum in Rust is a type that represents data that could be one of
several possible variants:

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

Each variant can optionally have data associated with it. The syntax for
defining variants resembles the syntaxes used to define structs: you can
have variants with no data (like unit-like structs), variants with named
data, and variants with unnamed data (like tuple structs). Unlike
separate struct definitions, however, an enum is a single type. A
value of the enum can match any of the variants. For this reason, an
enum is sometimes called a ‘sum type’: the set of possible values of the
enum is the sum of the sets of possible values for each variant.

We use the :: syntax to use the name of each variant: they’re scoped by the name
of the enum itself. This allows both of these to work:

# enum Message {
#     Move { x: i32, y: i32 },
# }
let x: Message = Message::Move { x: 3, y: 4 };

enum BoardGameTurn {
    Move { squares: i32 },
    Pass,
}

let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };

Both variants are named Move, but since they’re scoped to the name of
the enum, they can both be used without conflict.

A value of an enum type contains information about which variant it is,
in addition to any data associated with that variant. This is sometimes
referred to as a ‘tagged union’, since the data includes a ‘tag’
indicating what type it is. The compiler uses this information to
enforce that you’re accessing the data in the enum safely. For instance,
you can’t simply try to destructure a value as if it were one of the
possible variants:

fn process_color_change(msg: Message) {
    let Message::ChangeColor(r, g, b) = msg; // compile-time error
}

Not supporting these operations may seem rather limiting, but it’s a limitation
which we can overcome. There are two ways: by implementing equality ourselves,
or by pattern matching variants with <code>match</code> expressions, which you’ll
learn in the next section. We don’t know enough about Rust to implement
equality yet, but we’ll find out in the <code>traits</code> section.

Constructors as functions

An enum’s constructors can also be used like functions. For example:

# enum Message {
# Write(String),
# }
let m = Message::Write("Hello, world".to_string());

Is the same as

# enum Message {
# Write(String),
# }
fn foo(x: String) -> Message {
    Message::Write(x)
}

let x = foo("Hello, world".to_string());

This is not immediately useful to us, but when we get to
<code>closures</code>, we’ll talk about passing functions as arguments to
other functions. For example, with <code>iterators</code>, we can do this
to convert a vector of Strings into a vector of Message::Writes:

# enum Message {
# Write(String),
# }

let v = vec!["Hello".to_string(), "World".to_string()];

let v1: Vec<Message> = v.into_iter().map(Message::Write).collect();
Updated by djKooks about 4 years (view history)
5.12. 구조체 (Structs) - 100% 5.14. 정합 (Match) - 99%

Contents

    Rust 문서 한글화 프로젝트 1. 소개(Introduction) - 100% 2. 시작하기(Getting Started) - 100% 2.1. Rust 설치하기 (Installing Rust) - 100% 2.2. 안녕, 세상아! (Hello, world!) - 100% 2.3. 안녕, 카고! (Hello, Cargo!) - 100% 3. Rust 배우기 (Learn Rust) - 100% 3.1. 추리 게임 (Guessing Game) - 100% 3.2. 철학자들의 만찬 (Dining Philosophers) - 100% 3.3. 다른 언어에 Rust 포함하기 (Rust Inside Other Languages) - 100% 4. 효과적인 Rust (Effective Rust) - 100% 4.1. 스택과 힙 (The Stack and the Heap) - 100% 4.2. 테스팅 (Testing) - 50% 4.3. 조건부 컴파일 (Conditional Compilation) - 30% 4.4. 문서화 (Documentation) - 15% 4.5. 반복자 (Iterators) - 100% 4.6. 동시성 (Concurrency) - 100% 4.7. 오류 처리 (Error Handling) - 99% 4.8. 외부 함수 인터페이스 (Foreign Function Interface) - 60% 4.9. Borrow and AsRef 4.10. 배포 채널 (Release Channels) - 100% 5. 문법과 의미 (Syntax and Semantics) - 100% 5.1. 변수 바인딩 (Variable Bindings) - 90% 5.2. 함수 (Functions) - 50% 5.3. 기본형 (Primitive Types) - 100% 5.4. 주석 (Comments) - 100% 5.5. 조건식 (if) - 100% 5.6. for 반복문 (for Loops) - 100% 5.7. while 반복문 (while Loops) - 100% 5.8. 소유권 (Ownership) - 100% 5.9. 참조와 빌림 (References and Borrowing) - 100% 5.10. 수명 (Lifetimes) - 100% 5.11. 가변성 (Mutability) - 99% 5.12. 구조체 (Structs) - 100% 5.13. 열거형 (Enums) - 0% 5.14. 정합 (Match) - 99% 5.15. 패턴 (Patterns) - 100% 5.16. 메소드 문법 (Method Syntax) - 100% 5.17. 벡터 (Vectors) - 100% 5.18. 문자열(Strings) - 80% 5.19. 제너릭 (Generics) - 100% 5.20. 트레잇 (Traits) - 100% 5.21. 드랍 (Drop) - 100% 5.22. if let 5.23. 트레잇 객체 (Trait Objects) 5.24. 클로저 (Closures) - 10% 5.25. Universal Function Call Syntax 5.26. Crates and Modules 9. 용어 색인 (Concordance) Show all
    Discussions 5 Pending changes 5 Contributors
    Download Share

    Download

    Working...

    Downloading...

    Downloaded!

    Download more

    Error!

    Your download couldn't be processed. Check for abnormalities and incorrect syntax. We've been notified of the issue.

    Back

    Download PDF Download ePub Download HTML Download Word doc Download text Download source (archive)

    Close
456 Words
3,080 Characters

Share

Collaborators make changes on their own versions, and all changes will be approved before merged into the main version.

Close

Penflip is made by Loren Burton
in Los Angeles, California

Tweet

    About

  • Team
  • Pricing
  • Our Story

    Quick Start

  • Markdown
  • Penflip Basics
  • Working Offline

    Support

  • Help
  • Feedback
  • Terms & Privacy

    Connect

  • Email
  • Twitter