Getting To Know About Structs
Examine how structs work in Go, along with a brief overview of constructors.
Introduction
Structs represent a collection of variables. In the real world, we work with data all the time that would be well represented by a struct. For example, any form that is filled out in a job application or a vaccine card is a collection of variables (for example, last name, first name, and government ID number) that each has types (for example, string
, int
, and float64
) and are grouped together. That grouping would be a struct in Go.
Declaring a struct
There are two methods for declaring a struct. The first way is uncommon except in tests, as it doesn't allow us to reuse the struct's definition to create more variables. But, as we'll see it later in tests, we'll cover it here:
var record = struct{Name stringAge int} {Name: "John Doak",Age: 100, // Yeah, not publishing the real one}
Here, we created a struct that contains two fields:
Name
(string
)Age
(int
)
We then created an instance of that struct that has those values set. To access those fields, we can use the dot .
operator:
package mainimport "fmt"func main() {var record = struct{Name stringAge int}{Name: "John Doak",Age: 100,}fmt.Printf("%s is %d years old\n", record.Name, record.Age)}
Declaring single-use structs, as we have here, is rarely done. Structs become more useful when they are used to create custom types in Go that are reusable. Let's have a look at how we can do that next.