Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Slice of Struct in Go (Golang)

Posted on July 14, 2023July 14, 2023 by admin

Table of Contents

  • Overview
  • Program

Overview

It is possible to create a slice of struct in Golang as well. In fact, a slice can be created of any data type in Go. Below is a simple example to create a slice of structs

Program

package main
import "fmt"
type employee struct {
name string
age int
}
func main() {
employees := make([]employee, 3)
employees[0] = employee{name: "John", age: 21}
employees[1] = employee{name: "Simon", age: 25}
employees[2] = employee{name: "David", age: 18}
for _, e := range employees {
fmt.Println(e)
}
}

Output

{John 21}
{Simon 25}
{David 18}

In the above program, we created a struct named employee

type employee struct {
name string
age int
}

Then we created a slice of struct like this

employees := make([]employee, 3)

This is how we can create a slice of struct

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang – Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you –All Design Patterns Golang

  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP