Chapter 11. what can you do?: Interfaces
Sometimes you don’t care about the particular type of a value. You don’t care about what it is. You just need to know that it will be able to do certain things. That you’ll be able to call certain methods on it. You don’t care whether you have a
Pen or a
Pencil, you just need something with a
Draw method. You don’t care whether you have a
Car or a
Boat, you just need something with a
That’s what Go interfaces accomplish. They let you define variables and function parameters that will hold any type, as long as that type defines certain methods.
Two different types that have the same methods
Remember audio tape recorders? (We suppose some of you will be too young.) They were great, though. They let you easily record all your favorite songs together on a single tape, even if they were by different artists. Of course, the recorders were usually too bulky to carry around with you. If you wanted to take your tapes on the go, you needed a separate, battery-powered tape player. Those usually didn’t have recording capabilities. Ah, but it was so great making custom mixtapes and sharing them with your friends!
We’re so overwhelmed with nostalgia that we’ve created a
gadget package to help us reminisce. It includes a type that simulates ...