Lesson 22. Go’s got no class

 

After reading lesson 22, you’ll be able to

  • Write methods that provide behavior to structured data
  • Apply principles of object-oriented design

Go isn’t like classical languages. It has no classes and no objects, and it omits features like inheritance. Yet Go still provides what you need to apply ideas from object-oriented design. This lesson explores the combination of structures with methods.

Consider this

Synergy is a buzzword commonly heard in entrepreneurial circles. It means “greater than the sum of its parts.” The Go language has types, methods on types, and structures. Together, these provide much of the functionality that classes do for other languages, without needing to introduce a new concept into the language.

What other aspects of Go exhibit this property of combining to create something greater?

22.1. Attaching methods to structures

In lesson 13, you attached celsius and fahrenheit methods to the kelvin type to convert temperatures. In the same way, methods can be attached to other types you declare. It works the same whether the underlying type is a float64 or a struct.

To start, you need to declare a type, such as the coordinate structure in the following listing.

Listing 22.1. The coordinate type: coordinate.go
// coordinate in degrees, minutes, seconds in a N/S/E/W hemisphere.
type coordinate struct {
    d, m, s float64
    h       rune
}

22.2. Constructor functions

22.3. The class alternative

Summary