Lesson 24. Interfaces

 

After reading lesson 24, you’ll be able to

  • Get your types talking
  • Discover interfaces as you go
  • Explore interfaces in the standard library
  • Save humanity from a Martian invasion

Pen and paper aren’t the only tools you could use to jot down your latest insight. A nearby crayon and napkin can serve the purpose. Crayons, permanent markers, and mechanical pencils can all satisfy your need to write a reminder in a notepad, a slogan on construction paper, or an entry in a journal. Writing is very flexible.

The Go standard library has an interface for writing. It goes by the name of Writer, and with it you can write text, images, comma-separated values (CSV), compressed archives, and more. You can write to the screen, a file on disk, or a response to a web request. With the help of a single interface, Go can write any number of things to any number of places. Writer is very flexible.

A 0.5 mm ballpoint pen with blue ink is a concrete thing, whereas a writing instrument is a fuzzier idea. With interfaces, code can express abstract concepts such as a thing that writes. Think of what something can do, rather than what it is. This way of thinking, as expressed through interfaces, will help your code to adapt to change.

Consider this

What are some concrete things around you? What can you do with them? Can you do the same thing with something else? What is the common behavior or interface that they have?

24.1. The interface type

24.2. Discovering the interface

24.3. Satisfying interfaces

24.4. Summary