Lesson 21. A little structure

 

After reading lesson 21, you’ll be able to

  • Give coordinates on Mars a little structure
  • Encode structures to the popular JSON data format

A vehicle is made up of many parts, and those parts may have associated values (or state). The engine is on, the wheels are turning, the battery is fully charged. Using a separate variable for each value is akin to the vehicle sitting in the shop disassembled. Likewise, a building may have windows that are open and a door that is unlocked. To assemble the parts or construct a structure, Go provides a structure type.

Consider this

Whereas collections are of the same type, structures allow you to group disparate things together. Take a look around. What do you see that could be represented with a structure?

21.1. Declaring a structure

A pair of coordinates are good candidates for adopting a little structure. Latitude and longitude go everywhere together. In a world without structures, a function to calculate the distance between two locations would need two pairs of coordinates:

func distance(lat1, long1, lat2, long2 float64) float64

Though this does work, passing independent coordinates around is prone to errors and just plain tedious. Latitude and longitude are a single unit, and structures let you treat them as such.

21.2. Reusing structures with types

21.3. Initialize structures with composite literals

21.4. Structures are copied

21.5. A slice of structures

21.6. Encoding structures to JSON

21.7. Customizing JSON with struct tags

Summary