4 Building your own types

 

This chapter covers

  • Structs, which you can use to group values to build your own types
  • Enums, which are similar syntax to structs but used for choices, not groupings
  • Implementing types, which gives methods to your structs and enums
  • More on destructuring and taking types apart
  • References and the dot operator

It’s now time to look at the main ways to build your own types in Rust: structs and enums. You’ll also learn how to implement functions attached to and called on these types, called methods. These methods use the keyword self a lot, so get ready to see it!

4.1 A quick overview of structs and enums

Structs and enums have a similar syntax and are easiest to learn together, so that’s what we’ll do here. They also work together because structs can contain enums, and enums can contain structs. Because they look similar, sometimes users new to Rust confuse them. But here’s a rule of thumb to start: if you have a lot of things to group together, that’s a struct, but if you have a lot of choices and need to select one, that’s an enum.

If this book, Learn Rust in a Month of Lunches, were a struct, it would have its own properties, too. It would have a title (that’s a String), an author_name (also a String), and a year_of_publication (maybe an i32). But it also has more than one way to buy it: you can choose to buy it either as a printed book or as an eBook. That’s an enum! So keep that simple example in mind as we learn how structs and enums work.

4.1.1 Structs

4.1.2 Enums

4.1.3 Casting enums into integers

4.1.4 Enums to use multiple types

4.1.5 Implementing structs and enums

4.2 Destructuring

4.3 References and the dot operator

sitemap