Mahdi.Kh
September 21, 2026
We get familiar with the struct data type and learn how, similar to object-oriented programming languages, we can model objects using struct.
In Golang, the struct data type is a composite type used to group a set of related values under one name. These values, called a struct's fields, can have different data types.
The general structure of a struct is as follows:
For example, we can define a struct named Person that has two fields, Age and Name:
In the example above, we first defined a struct named Person with two fields, Name and Age. We defined a variable named x of type Person, printed its zero value once, and then set and printed each field separately.
A struct's zero value is made up of the zero values of its fields. We can also assign the variable above as follows:
A struct can be created without giving it a name; this is called an anonymous struct. We just need to define the struct and assign it to a variable at the same time.
Note that an anonymous struct isn't reusable, meaning if we want to define another variable with the same data type, we have to repeat the struct's structure again!
There are two ways to use a struct in a nested fashion:
A struct can have several fields, and each of these fields can also be of struct type.
In Go, you can add methods to any type you've defined, and structs are no different. The previous example can be rewritten using a method as follows:
In the example above, we added a method named Print to UsersCollection. This method prints this struct's items on the screen.
A method can access the data type it belongs to through its receiver argument. The receiver argument is really a variable of the data type the method belongs to. If we define the receiver as a pointer, we can change the struct's data through the method.
In the IncreaseAge method, we used a pointer type for the receiver argument so we could change Age.
Every method can be stored in a variable and called:
You can also assign a data type's methods to a variable, and then call the method stored in that variable with receivers of the same data type.
Previous part: Functions | Golang basics
Next part: Interfaces | Golang basics