Golang Array of Structs

Sheeraz Gul Sep 28, 2022
Golang Array of Structs

This tutorial demonstrates how to create and use an array of structs in Golang.

Create an Array of Structs in Golang

The struct is considered a user-defined type in Golang, which is used to store different types of data in one type. This concept is usually used in the OOP, where we use a class to store multiple types of data or their properties.

In Golang, we can use the struct, which will store any real-world entity with a set of properties. Golang has the functionality to set the struct of an array.

For example:

type Delftstack struct {
    SiteName  string
    tutorials []tutorial
}

type tutorial struct {
    tutorialName     string
    tutorialId       int
    tutorialLanguage string
}

The code above shows the type Delftstack struct uses the slice of type tutorial struct, where the tutorial struct is used as an array. These can also be considered nested structs.

Let’s try an example that shows how to use the array of structs in our code:

package main

import "fmt"

type Delftstack struct {
	SiteName  string
	tutorials []tutorial
}

type tutorial struct {
	tutorialName     string
	tutorialId       int
	tutorialLanguage string
}

func main() {
	PythonTutorial := tutorial{"Introduction to Python", 10, "Python"}
	JavaTutorial := tutorial{"Introduction to Java", 20, "Java"}
	GOTutorial := tutorial{"Introduction to Golang", 30, "Golang"}

	tutorials := []tutorial{PythonTutorial, JavaTutorial, GOTutorial}
	Delftstack := Delftstack{"Delftstack.com", tutorials}

	fmt.Printf("The site with tutorials is %v", Delftstack)
}

The code above initializes a struct Delftstack and then uses the array of struct tutorial in the Delftstack struct. Finally, it prints the site name with the array of tutorials.

See the output:

The site with tutorials is {Delftstack.com [{Introduction to Python 10 Python} {Introduction to Java 20 Java} {Introduction to Golang 30 Golang}]}
Program exited.
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Go Struct

Related Article - Go Array