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?
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:
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.