Structs, enums and pattern matching
Rust’s type system is where the design of a program happens. An enum with data turns invalid states into code that will not compile; a newtype makes an id impossible to confuse with another id.
The match articles are the ones to read first, because that is where you spend the time.
Articles
Section titled “Articles”Nothing published in this chapter yet — all 26 articles are still to come.
Coming up (26)
- What is the difference between a struct and an enum?all of these fields, or one of these shapes
- What is the difference between a method and an associated function?the self parameter, and what it costs you
- How to initialise a struct field from a variable with the same namefield init shorthand
- What is the struct update syntax?..other, and the fields it moves
- How to derive Debug for a structand what to do when a field has no Debug
- How to make a struct comparable and sortablethe five derives, and the field that blocks one
- What are tuple structs?a named type with unnamed fields
- How to attach data to enum variantseach variant carries its own shape
- What is the difference between Option and null?the compiler makes you handle it
- How to use match with enumsexhaustive, and the arm you will forget
- How to use if let and let elseone arm instead of two, and the early return
- How to match multiple patterns with the or operatoror-patterns, and the binding that has to match too
- How to match ranges of values1..=5 in an arm, and the overlap rule
- How to destructure structs and enums in a matchpulling fields out in the pattern
- How to use matches! to check a patterna boolean without a match block
- When should you use an enum instead of a struct?the “one of these” test
- How to model state machines with enumsinvalid states become unrepresentable
- How to implement Display for a custom typefmt::Display, and why an error type needs Error too
- How to convert between types with From and Intoimplement one, get the other
- How to implement Default for a structDefault::default(), and the derive limit
- How to use the builder patternchained setters that end in build()
- What is the newtype pattern?a one-field struct that buys you type safety
- How to implement operator overloadingimpl Add for a vector type
- How to use type aliasesa shorter name, not a new type
- How to return two values from a functiona tuple, or a named struct
- How to destructure a tuplebinding several names in one let