The Go Programming Language Specification
Making slices, maps and channels
The built-in function make takes a type T, which must be a slice, map
or channel type, optionally followed by a type-specific list of
expressions. It returns a value of type T (not *T). The memory is
initialized as described in the section on initial values.
Call Type T Result
make(T, n) slice slice of type T with length n and capacity n
make(T, n, m) slice slice of type T with length n and capacity m
The size arguments n and m must be of integer type or untyped. A
constant size argument must be non-negative and representable by a
value of type int. If both n and m are provided and are constant, then
n must be no larger than m. If n is negative or larger than m at run
time, a run-time panic occurs.
s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000
s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int
s := make([]int, 10, 0) // illegal: len(s) > cap(s)
For example,
package main
import "fmt"
func main() {
s := make([]int, 7, 42)
fmt.Println(len(s), cap(s))
t := make([]int, 100)
fmt.Println(len(t), cap(t))
}
Output:
7 42
100 100
[100]int
is not a slice, it's an array.[]int
is a slice. Please consider reading blog.golang.org/slices and blog.golang.org/go-slices-usage-and-internalsslice
is a scoped view of an array. The array can either be explicit, as in:var a [100]int
- array of int, len==100 ,s := a[25:50]
- slice ofa
, giving access to elements 25.. 49 ofa
, or implicit, as in:s := make([]int, 10, 100)
- slice with access to 10 elements of the array implicitly allocated by the second parameter ofmake()
-capacity
.