Chapter 10. Enums and Patterns

The first topic of this chapter is potent, as old as the hills, happy to help you get a lot done in short order (for a price), and known by many names in many cultures. But it’s not the devil. It’s a kind of user-defined data type, long known to ML and Haskell hackers as sum types, discriminated unions, or algebraic data types. In Rust, they are called enumerations, or simply enums. Unlike the devil, they are quite safe, and the price they ask is no great privation.

열거형 데이터 타입 Enumeration

C++ and C# have enums; you can urse them to define your own type whose values are a set of named constants. For example, you might define a type named Color with values Red, Orange, Yellow, and so on. This kind of enum works in Rust, too. But Rust takes enums much further. A Rust enum can also contain data, even data of varying types. For example, Rust’s Result<String, io::Error> type is an enum; such a value is either an Ok value containing a String or an Err value containing an io::Error. This is beyond what C++ and C# enums can do. It’s more like a C union —but unlike unions, Rust enums are type-safe.

일반적인 열거형 데이터 타입은 값이 명명된 상수 집합이지만, Rust에서는 다양한 유형의 데이터도 포함될 수 있다. Result<String, io::Error> 유형 또한 열거형이 될 수 있다. 이 값은 Ok 혹은 Err 값이다.

Enums are useful whenever a value might be either one thing or another. The “price” of using them is that you must access the data safely, using pattern matching, our topic for the second half of this chapter.

열거형을 사용할 때 주의할 점은 ‘패턴 일치’를 사용하여 데이터에 안전하게 액세스해야 한다는 점이다.

Patterns, too, may be familiar if you’ve used unpacking in Python or destructuring in JavaScript, but Rust takes patterns further. Rust patterns are a little like regular expressions for all your data. They’re used to test whether or not a value has a particular desired shape. They can extract several fields from a struct or tuple into local variables all at once. And like regular expressions, they are concise, typically doing it all in a single line of code.

Rust는 패턴을 더 발전시킨다. Rust 패턴은 정규식과 약간 비슷한데, 값이 원하는 특정 모양을 가지고 있는지 여부를 테스트하는 데 사용된다. 구조체나 튜플의 여러 필드를 로컬 변수로 추출할 수 있고 정규식처럼 간결하다.

This chapter starts with the basics of enums, showing how data can be associated with enum variants and how enums are stored in memory. Then we’ll show how Rust’s patterns and match statements can concisely specify logic based on enums, structs, arrays, and slices. Patterns can also include references, moves, and if conditions, making them even more capable.

이 장에서는 열거형, 열거형 변형, 열거형 저장, 패턴 활용법 등을 배울 예정이다.

Enums

Simple, C-style enums are straightforward: