Golang Basics - Structs

What we went over until now were all the primitive types provided by Go. For more complex programs, you would need to represent variables that are composed of multiple primitive types.

For example, a vehicle could be represented by its brand and the number of wheels it contains. We can use structs to represent this type of data:

// To define a struct, we use the `struct` keyword:
type Vehicle struct{
        Model string
        Wheels int
}
// this defines a new type `Vehicle` with the struct definition

// next we define a variable of type `Vehicle`
var car Vehicle

// And assign it's value
car = Vehicle{
        Model: "Toyota",
        Wheels: 4,
}

// We can also use the `:=` operator as a shorthand:
bike := Vehicle{
        Model: "Ducati",
        Wheels: 2,
}

// We can access individual properties of a struct using the `.` operator

fmt.Println(car.Model)
// "Toyota"

fmt.Println(bike.Wheels)
// 2

The default value of a struct is the composition of the individual default values of its contents. For example, the default value for a Vehicle type would be:

Vehicle{
        Model: "",
        Wheels: 0,
}

Structs can also compose other structs. Let's say we want to represent the owner of the vehicle, with a name and the information about the vehicle they own:

// This declares an owner type with a Name field of type string, and and OwnedVehicle field of type Vehicle
type Owner struct {
        Name string
        OwnedVehicle Vehicle
}

// We can then declare a new instance of an owner
o := Owner{
        Name: "Joe",
        OwnedVehicle: Vehicle{
                Model: "Tesla",
                Wheels: 4,
        },
}

// We can access embedded properties as well
fmt.Println(o.OwnedVehicle.Model)
// "Tesla"

📖 Read next: Pointers


Liked this article? Share it on: