DEV Community

Cover image for Create a slice with make
bluepaperbirds
bluepaperbirds

Posted on

2 1

Create a slice with make

In the Go programming language you can create arrays: collections.

You can create slices with the built-in make() function; you can create dynamically-sized arrays this way.

Remember that the usual array has a fixed size, that you would define in one of these two ways:

var a [10]int
var a = []int64{ 1,2,3,4 }

What if you want an array that contains zeroes?

Make() in Go

The make function allocates a zeroed array and returns a slice that refers to that array. The syntax of the make() function is:

your_array := make([]type, length)

So if you'd have a program like this:

package main

import "fmt"

func main() {
    a := make([]int, 5)
    printSlice("a", a)

}

func printSlice(s string, x []int) {
    fmt.Printf("%s len=%d cap=%d %v\n",
        s, len(x), cap(x), x)
}

It would output the array (contains a lot of zeros, the make() function does this):

a len=5 cap=5 [0 0 0 0 0]

To change its size, change the second parameter

a := make([]int, 50)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay