Structs in Go

Alissa LozhkinAlissa Lozhkin
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 {
    name 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}
0
Subscribe to my newsletter

Read articles from Alissa Lozhkin directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alissa Lozhkin
Alissa Lozhkin

My name is Alissa and I am a fourth-year computer science and math student at the University of Toronto! I am very interested in computer science and software development, and I love learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin