Go comes built-in with a number of Primitive and Composite Data Types. However, you can also create your own custom user-defined data types, and that’s done using Structs.
This article is part of the Data Types in Go series.
Structs (short for “structure”) lets you create composite data types for storing a collection of key-value pairs. Structs are often used for representing real-world entities.
Structs are defined using the
type statement (lines 10–16). After that, you can use your new data type to create variables (lines 18–24).
Line 10: We used the
type statement to define a struct called employee. The
type statement also means we’re defining a custom data type. That means that Go views “employee” as just another data type, similar to integers, strings, booleans…etc.
Lines 11–15: Each line defines a key-value pair. Each entry comprises 2 fields, the key’s name, followed by the data type, e.g. the key “smoker” can store boolean values. I like to imagine each entry in the form of a box, where the first field (e.g. “smoker”) is written on the box’s lid, and the second field (e.g. boolean) specifies what type of values the box is allowed to store.
Line 18: We’ve declared a variable called dave. This is an instance of the “employee” struct.
Line 26: This prints out all the values in curly braces, as shown in the output.
Line 27–28: The
. operator is used for accessing a particular key’s value.
Line 31: Our struct variable’s data type is
main.employee. The package’s name (main) is also included here since it’s the “main” packages struct definition was used to create this “dave” variable.
I like to think of a struct definition (e.g. lines 18-24) as a blueprint for creating instances of the “employee” data type.
Structs in short-hand form
You can write both your struct definition and declarations in shorthand form, but it does make the code harder to read. Here’s the previous example written in more compact form:
Lines 10–14: All keys whose values are of the same data type (e.g. “id” and “age”), are grouped and defined on a single line.
Line 16: Omitting the key names allows us to declare all the values on a single line. The values' order now needs to align with the ordering in the struct’s definition (lines 10–24).
Line 18: The ordering of the printout is slightly different this time, only because we had to reorder the keys in the struct’s definition itself (lines 10–24) so to group the keys based on the data types.
You can also use the
fmt.Printf("%+v\n", myStruct) technique to “pretty print” a struct, here’s an example.
More about Structs
That cover’s the basics of structs. To learn more, check out: