A struct is a data type in Golang, it can also be compared to a class in an object oriented programming language. A struct gives us the ability to set specific fields for a type of data.
For example, if we have a struct called Employee, we would have defined fields of: first name, last name, salary, age etc..
To define that in Golang is as simple as:
Then, to create an instance of that class, we can pass values into a curly brace like below. Here, we’re creating a new employee called emp1. This is a instance of the employee struct we just created. Here, I have passed the values in without field labels – this means they MUST remain in the order that they’re defined in the struct.
We can get around this by passing in the field names. This is much safer for us to do as it does not require us to pass the values in any particular order, so human error will not result in the data being inserted incorrectly.
To print data from our struct, we can call a particular field. For example: fmt.Println(emp2.firstName) will print ‘Carl’.
A pretty useful feature is being able to embed structs within structs. You can see below, I am defining two new structs. The first is a details struct. This holds contact details for the employee.
Below that, I have defined a struct called detailed_emp and have passed the details struct into it with the field label of ‘contact’. You don’t strictly have to pass a field label, if you don’t set the label for a struct field, it will inherit the name of the struct, in this case, it would be ‘details’.
We can now create an employee with these details populated. If we wanted to access email from this, we could do fmt.Println(emp_with_contact_info.contact.email).