Chapter 10. keep it to yourself: Encapsulation and Embedding

image

Mistakes happen. Sometimes, your program will receive invalid data from user input, a file you’re reading in, or elsewhere. In this chapter, you’ll learn about encapsulation: a way to protect your struct type’s fields from that invalid data. That way, you’ll know your field data is safe to work with!

We’ll also show you how to embed other types within your struct type. If your struct type needs methods that already exist on another type, you don’t have to copy and paste the method code. You can embed the other type within your struct type, and then use the embedded type’s methods just as if they were defined on your own type!

Creating a Date struct type

A local startup called Remind Me is developing a calendar application to help users remember birthdays, anniversaries, and more.

image

The year, month, and day sound like they all need to be grouped together; none of those values would be useful by itself. A struct type would probably be useful for keeping those separate values together in a single bundle.

As we’ve seen, defined types can use any other type as their underlying type, including structs. In fact, struct types served as our introduction to defined types, back in Chapter 8.

Let’s create a Date struct type to ...

Get Head First Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.