Go — structs (basics)

Go’s structs are used to describe certain pieces of data or relationships or functionality on data contained within that struct.

Given the example below, for a struct named “car”:

We can then create a function that acts as a constructor, creating a new instantiated car struct for us:

The function: “newCar” takes in a name of type string, and returns us a new car, with an age of 0 (notice the comment).

When instantiating a new “car” struct, you don't actually need to give the name of the parameters, like “name” and “age”, though it's recommended to show explicitly which parameter the value is assigned to:

As described in the previous post about pointers you can also pass a pointer to the newly created car struct:

Then when you want to access the values stored in a struct you use the dot notation:

Not only can you access the values stored in a struct, but you can also change/update these values:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nikolaj Johannes Skole Jensen

Fullstack developer living in Denmark. Experience with both Web- and App development.