O'Reilly logo

Head First Go by Jay McGavren

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9 defined types

You're My Type

Images

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 U.S.A., you are probably used to the quirky system of measurement used here. 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.

Images

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 37.85 liters ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required