golang

How to use array of structs in GoLang


In this article, you will learn about how to use an array of structs in the Go Language.

In the Go language, a struct is defined as a user-defined type that allows storing different types of values into a single type.

In Object-Oriented Programming languages, you may hear about the class that is used to store multiple data type properties. You may use any real-world entity as a struct that has a set of properties.

In the Go language, you can set a struct of an array. To do so see the below code example. Where type company struct has a slice of type employee struct.

type company struct {
        companyName string
        employees   []employee
}

type employee struct {
        name     string
        salary   int
        position string
}

Here, you can see the two different structs, and the employee struct is used as an array in the company struct. It is one kind of nested structs. Let’s see the below code example of how you can initialize a struct and how to use this array of structs.

package main

import "fmt"

type company struct {
        companyName string
        employees   []employee
}

type employee struct {
        name     string
        salary   int
        position string
}

func main() {
        deven := employee{"Deven", 10000, "Full-Stack Developer"}
        alex := employee{"Alex", 7000, "Back-end Developer"}

        employees := []employee{deven, alex}
        company := company{"ABC", employees}

        fmt.Printf("Company is %v\\n", company)
}

//Output: Company is {ABC [{Deven 10000 Full-Stack Developer} {Alex 7000 Back-end Developer}]}

Here, in the output, you can see that the company name is printed first and then the array of the employee printed with details and by following this approach, you may use an array of structs in the Go language.


Share on social media

//