How to initialize a slice in Golang

Last updated on Jun 19, 2021 by Suraj Sharma



In this tutorial, you will learn to initialize a slice or a dynamically-sized array in Golang using a built-in make function.

To initialize a slice, the make function accepts 3 arguments, first argument is the slice elements type, second argument is the initial length of the slice and, an optional third argument is the capacity of the slice.


Create a Slice


Consider, a Post struct type


type Post struct {
    ID      uint     `json:"id"`
    Title   string   `json:"title"`
    Author  string   `json:"author"`
    Content string   `json:"content"`
}


First, we will create a slice of elements of Post type, with an initial length of 0 and then, we will append a new post to the slice


import "fmt"

func main () {
    posts := make([]Post, 0)
    posts = append(posts, Post{
        1,
        "Slice Initialization",
        "Suraj Sharma",
        "Initialize slice using make function",
    })

    fmt.Println(posts)
  // [{1 Slice Initialization Suraj Sharma Initialize slice using make function}]

  fmt.Println(len(posts)) // 1

}


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.