Chapter 9. you’re my type: Defined Types

image

There’s more to learn about defined types. In the previous chapter, we showed you how to define a type with a struct underlying type. What we didn’t show you was that you can use any type as an underlying type.

And do you remember methods—the special kind of function that’s associated with values of a particular type? We’ve been calling methods on various values throughout the book, but we haven’t shown you how to define your own methods. In this chapter, we’re going to fix all of that. Let’s get started!

Type errors in real life

If you live in the US, you are probably used to the quirky system of measurement used there. At gas stations, for example, fuel is sold by the gallon, a volume nearly four times the size of the liter used in much of the rest of the world.

Steve is an American, renting a car in another country. He pulls into a gas station to refuel. He intends to purchase 10 gallons, figuring that will be enough to reach his hotel in another city.

image

He gets back on the road, but only gets one-fourth of the way to his destination before running out of fuel.

If Steve had looked at the labels on the gas pump more closely, he would have realized that it was measuring the fuel in liters, not gallons, and that he needed to purchase ...

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.