Working with Struct in Go

11.15.2021

Intro

In Go, structs allow you to create your own data types by grouping multiple types together. For example, we can create a person struct to hold a first name, last name, and more. In this article, we will learn how to use structs.

Declaring a Struct

Let's start by creating an example person struct that we talked about above.

type Person struct {
	firstName string
	lastName string
	age int
}

As you can see, we use the type keyword indicating this will be a type and the struct to declare the structure.

Creating a Struct Instances

Now that we have defined a struct, we create multiple instance of a struct. We do this by creating variables of our new type. We can then modify the properties using the . dot operator.

var person1 Person
person1.firstName = "Jane"
person1.lastName = "Doe"
person1.age = 20

fmt.Println(person1)

var person2 Person
person2.firstName = "Jon"
person2.lastName = "Doe"
person2.age = 20

fmt.Println(person2)

We can also create instances using the struct literal. Here is an example using positionals where each value lines up with the order pf properties.

person3 := Person{"Jane", "Doe", 20}
fmt.Println(person3) 

We can also use named arguments. Also not, we do not have to provide a value for each property.

person3 := Person{firstName: "Jane", age: 20}
fmt.Println(person3) 

Adding Methods to Struct

We can add methods to our struct definition by defining a function with a method receiver. Let's see an example.

func (p Person) PrintInfo() string {
	fmt.Println("Name: ", p.firstName, " Age: ", p.age)
	return "----"
}

Notice that we add (p Person) to the left of our method name. This allows us to use the method on any instance of our struct.

person3 := Person{firstName: "Jane", age: 20}
person3.PrintInfo()

The Full Example

Here is the full example code. You can run this by copying the contents into a file called main.go and then running go run main.go.

package main

import "fmt"

type Person struct {
	firstName string
	lastName  string
	age       int
}

func (p Person) PrintInfo() string {
	fmt.Println("Name: ", p.firstName, " Age: ", p.age)
	return "----"
}

func main() {
	var person1 Person
	person1.firstName = "Jane"
	person1.lastName = "Doe"
	person1.age = 20

	fmt.Println(person1)

	var person2 Person
	person2.firstName = "Jon"
	person2.lastName = "Doe"
	person2.age = 20

	fmt.Println(person2)

	person3 := Person{"Jane", "Doe", 20}
	fmt.Println(person3)

	person4 := Person{firstName: "Jane", age: 20}
	fmt.Println(person4)

	person5 := Person{firstName: "Jane", age: 20}
	person5.PrintInfo()
}