Lesson 13. Methods
After reading lesson 13, you’ll be able to
- Declare new types
- Rewrite functions as methods
Methods are like functions that enhance types with additional behavior. Before you can declare a method, you need to declare a new type. This lesson takes the kelvinToCelsius function from lesson 12 and transforms it into a type with methods.
At first it may look like methods are just a different syntax for doing what functions already do, and you would be right. Methods provide another way to organize code, an arguably nicer way for the examples in this lesson. Later lessons, those in unit 5 in particular, demonstrate how methods can be combined with other language features to bring new capabilities.
Consider this
When you type numbers on a calculator versus a typewriter, the expected behavior is quite different. Go has built-in functionality to operate on numbers and text (+) in unique ways, as demonstrated in lesson 10.
What if you want to represent a new type of thing and bundle behaviors with it? A float64 is too generic to adequately represent a thermometer, and a dog’s bark() is entirely different from the bark of a tree. Functions have a place, but types and methods provide another useful way to organize code and represent the world around you.
Before you start on this lesson, look around and consider the types around you and the behaviors they each have.