Skip to main content

Command Palette

Search for a command to run...

Structs in Go

Updated
1 min read

A struct is a composite datatype that groups together many fields of different types into one object. This blog post will go over the basics of how to declare a struct and assign values to its attributes.

In Go, a struct is defined using the type keyword. The general way of defining a struct is as follows:

type <struct_name> struct {
    // struct attributes
}

The code block below does two things: it defines a struct called person that has name (type string) and age (type int) as its attributes, and it declares an object of this type:

import "fmt"

type person struct {
    firstName string
    age int
}
person1 := person{firstName: "Anna", age: 35}

fmt.Println(person1)  // {Anna 35}
fmt.Println(person1.firstName)  // Anna
fmt.Println(person1.age)  // 35

Structs are also mutable, so we can change the value of a struct’s attribute:

import "fmt"

person2 := person{firstName: "Allison", age: 20}

fmt.Println(person2)  // {Allison 20}
person2.age += 1
fmt.Println(person2)  // {Allison 21}

It is possible that only one variable is a struct, and so it doesn’t make sense to give the struct a name. The following code block creates an object flower with attributes colour and petal_number:

import "fmt"

flower := struct {
    colour       string
    petal_number int
}{
    "blue",
    6,
}
fmt.Println(flower)  // {blue 6}

More from this blog

GoTech With Alissa

19 posts