ZetCode

Go make function

last modified October 30, 2026 Go 1.27

In this article we describe the make function and show how to use it with slices, maps and channels.

make is a built-in function that allocates and initializes a slice, a map or a channel. It returns a ready-to-use value of the requested type, already connected to its backing array, hash table or buffer.

func make(t Type, size ...IntegerType) Type

The meaning of the size argument depends on the type:

TypeFirst sizeSecond size
slicelengthcapacity (optional, at least the length)
mapinitial capacity hintnot allowed
channelbuffer capacity, 0 if omittednot allowed

All examples in this article were compiled and run with Go 1.27.0.

Creating a slice with a length

For a slice, make([]T, n) allocates a backing array of n elements, sets them to the zero value of T and returns a slice of length n that refers to it.

main.go
package main

import "fmt"

func main() {

    vals := make([]int, 5)
    fmt.Println(vals, len(vals), cap(vals))

    vals[0] = 12
    vals[4] = 38
    fmt.Println(vals)
}

The five elements exist from the start and hold zeros, so they can be assigned by index right away. This is the difference from a slice literal with no elements, which has length zero.

$ go run main.go
[0 0 0 0 0] 5 5
[12 0 0 0 38]

Length and capacity

The length is the number of elements the slice currently has; the capacity is the number of elements the backing array can hold before it has to be reallocated. make sets both, and they are equal when only the length is given.

main.go
package main

import "fmt"

func main() {

    a := make([]int, 3)
    fmt.Println(len(a), cap(a), a)

    b := make([]int, 0, 3)
    fmt.Println(len(b), cap(b), b)

    b = append(b, 7)
    fmt.Println(len(b), cap(b), b)

    c := make([]int, 2, 5)
    c = append(c, 9)
    fmt.Println(len(c), cap(c), c)
}

The second slice has room for three elements but none of them is part of the slice yet, so it prints as empty. Appending to it fills the existing array, which is why the capacity stays at three. The third slice already owns two zero-valued elements, and the appended value lands in the third slot.

$ go run main.go
3 3 [0 0 0]
0 3 []
1 3 [7]
3 5 [0 0 9]

Capacity growth when appending

A slice made with capacity zero starts without a backing array. The first append allocates one, and every time the capacity is exhausted Go allocates a larger array and copies the elements.

main.go
package main

import "fmt"

func main() {

    vals := make([]int, 0)

    for i := 1; i <= 5; i++ {
        vals = append(vals, i)
        fmt.Printf("len=%d cap=%d %v\n", len(vals), cap(vals), vals)
    }
}

The capacity grows 1, 2, 4, 8 for small slices. The exact sequence is an implementation detail and may change between Go releases, so programs should not depend on it; they should only rely on the capacity being at least the length.

$ go run main.go
len=1 cap=1 [1]
len=2 cap=2 [1 2]
len=3 cap=4 [1 2 3]
len=4 cap=4 [1 2 3 4]
len=5 cap=8 [1 2 3 4 5]

nil, empty and literal slices

Three slices can look the same when printed but behave differently: var s []int is nil, make([]int, 0) is empty but allocated, and []int{} is an empty literal. Appending works on all three, but only the allocated ones are non-nil.

main.go
package main

import (
    "fmt"
    "slices"
)

func main() {

    var nilSlice []int
    empty := make([]int, 0)
    literal := []int{}

    fmt.Println(nilSlice == nil, empty == nil, literal == nil)
    fmt.Println(len(nilSlice), len(empty), cap(nilSlice), cap(empty))
    fmt.Println(slices.Equal(nilSlice, empty))

    nilSlice = append(nilSlice, 1)
    fmt.Println(nilSlice)
}

A nil slice has no backing array, so cap reports zero. It is nevertheless usable: append allocates the array on the first call, and slices.Equal treats nil and empty as equal because both have no elements.

$ go run main.go
true false false
0 0 0 0
true
[1]

A two-dimensional grid

make([][]int, rows) creates a slice of nil slices. Every row has to be allocated separately, which also allows rows of different lengths.

main.go
package main

import "fmt"

func main() {

    grid := make([][]int, 3)

    for i := range grid {
        grid[i] = make([]int, 4)
    }

    grid[1][2] = 7

    for _, row := range grid {
        fmt.Println(row)
    }

    fmt.Println(len(grid), len(grid[0]), cap(grid))
}

Without the loop the rows would be nil and the assignment grid[1][2] = 7 would panic with an index out of range. The outer slice has its own length and capacity, independent of the rows.

$ go run main.go
[0 0 0 0]
[0 0 7 0]
[0 0 0 0]
3 4 3

Creating a map

For a map, the size argument is a hint about how many elements the map will hold. Go uses it to size the initial hash table, but the map still starts empty and can grow beyond the hint.

main.go
package main

import "fmt"

func main() {

    counts := make(map[string]int, 3)

    counts["apples"] = 12
    counts["oranges"] = 5
    counts["pears"] = 0

    fmt.Println(counts)
    fmt.Println(len(counts))

    delete(counts, "pears")
    fmt.Println(len(counts))
}

The hint does not reserve exactly three slots and is not visible through len: that function only counts the stored keys. A zero value stored under a key still counts, until the key is deleted.

$ go run main.go
map[apples:12 oranges:5 pears:0]
3
2

A nil map cannot be written

A map declared with var is nil. Reading from it is allowed and returns zero values, but writing to it panics, because there is no hash table to write into.

main.go
package main

import "fmt"

func main() {

    var counts map[string]int

    fmt.Println(counts == nil, len(counts), counts["apples"])

    counts["apples"] = 1
    fmt.Println(counts)
}

The panic happens at run time, not at compile time, and the message names the operation. Assigning make(map[string]int) or a literal to the variable fixes the program.

$ go run main.go
true 0 0
panic: assignment to entry in nil map

goroutine 1 [running]:
main.main()
    /home/user/main.go:11 +0xc5
exit status 2

Unbuffered and buffered channels

For a channel, the size is the buffer capacity. Without it the channel is unbuffered: a send blocks until another goroutine receives. With a buffer, sends succeed while there is free space.

main.go
package main

import "fmt"

func main() {

    unbuffered := make(chan int)
    buffered := make(chan int, 3)

    fmt.Println(cap(unbuffered), cap(buffered))
    fmt.Println(len(buffered))

    buffered <- 1
    buffered <- 2
    fmt.Println(len(buffered), cap(buffered))

    fmt.Println(<-buffered, <-buffered)
    fmt.Println(len(buffered))

    close(buffered)
    fmt.Println(len(buffered))
}

len on a channel reports how many values are waiting in the buffer, and cap reports the buffer size. Closing does not discard the buffered values; they can still be received, and the length stays zero here because both were already taken out.

$ go run main.go
0 3
0
2 3
1 2
0
0

A producer goroutine

A buffered channel lets a producer run ahead of the consumer. The example below sizes the buffer from the channel itself with cap, so the producer never blocks and the goroutine can finish before the values are read.

main.go
package main

import "fmt"

func fib(n int, c chan int) {

    x, y := 0, 1

    for i := 0; i < n; i++ {
        c <- x
        x, y = y, x+y
    }
    close(c)
}

func main() {

    c := make(chan int, 10)

    go fib(cap(c), c)

    for v := range c {
        fmt.Print(v, " ")
    }
    fmt.Println()
}

range over a channel receives values until the channel is closed. The producer closes it after the last send, which ends the loop in main. With an unbuffered channel the same program would work too, but the two goroutines would have to meet on every value.

$ go run main.go
0 1 1 2 3 5 8 13 21 34 

Deadlock from an unbuffered send

An unbuffered channel with no receiver blocks the sender forever. When the Go runtime detects that no goroutine can make progress, it stops the program with a deadlock error instead of hanging.

main.go
package main

import "fmt"

func main() {

    c := make(chan int)

    c <- 1
    fmt.Println(<-c)
}

The send on the third line waits for a receiver that can never arrive, because the only goroutine is the one that is blocked. Making the channel buffered with make(chan int, 1) would let the send complete and the program print 1.

$ go run main.go
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
    /home/user/main.go:9 +0x36
exit status 2

Invalid arguments

Constant arguments are checked by the compiler. A negative length, a capacity smaller than the length, or a type that cannot be made are all rejected before the program is built.

main.go
package main

func main() {
    a := make([]int, -1)
    b := make([]int, 5, 2)
    c := make(int)
    _, _, _ = a, b, c
}

The compiler reports one error per statement. It also rejects a make call with no size at all, because the length of a slice is not optional, and it cannot be used for arrays or structs.

$ go build main.go
# command-line-arguments
./main.go:4:22: invalid argument: index -1 (constant of type int) must not be negative
./main.go:5:22: invalid argument: length and capacity swapped
./main.go:6:15: invalid argument: cannot make int: type must be slice, map, or channel

When the values come from variables, the same mistakes become run-time panics with a different wording.

main.go
package main

import "fmt"

func main() {

    n := -1
    s := make([]int, n)
    fmt.Println(s)
}

The check happens in the makeslice runtime function. A capacity smaller than the length taken from variables produces makeslice: cap out of range in the same way.

$ go run main.go
panic: runtime error: makeslice: len out of range

goroutine 1 [running]:
main.main()
    /home/user/main.go:8 +0x25
exit status 2

make versus new

new(T) allocates a zero value of any type and returns a pointer to it. For a slice, new([]int) therefore returns a pointer to a nil slice, which is rarely what a program needs.

main.go
package main

import "fmt"

func main() {

    p := new([]int)
    *p = append(*p, 1)

    fmt.Printf("%T\n", p)
    fmt.Println(*p, len(*p), cap(*p))

    q := make([]int, 0, 4)
    fmt.Printf("%T\n", q)
    fmt.Println(len(q), cap(q))
}

make returns the slice itself, already backed by an array of the requested capacity, while new only reserves space for the slice header. For maps and channels new is almost always a bug, since the zero value is nil and cannot be used.

$ go run main.go
*[]int
[1] 1 1
[]int
0 4

Source

The Go specification - making slices, maps and channels

In this article we have used the make function to create slices with a length and a capacity, maps with a size hint, buffered and unbuffered channels, and we have shown the errors produced by invalid arguments.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.