Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare slice or make slice?

People also ask

How do you declare a slice?

A slice can be declare using new keyword followed by capacity in square brackets then type of elements the slice will hold.

How do you make slices in Go?

In Go language, a slice can be created and initialized using the following ways: Using slice literal: You can create a slice using the slice literal. The creation of slice literal is just like an array literal, but with one difference you are not allowed to specify the size of the slice in the square braces[].

How do you define a slice in Golang?

A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment). Our variable s , created earlier by make([]byte, 5) , is structured like this: The length is the number of elements referred to by the slice.

What is Go make?

Golang make() is a built-in slice function used to create a slice. The make() function takes three arguments: type, length, and capacity, and returns the slice. To create dynamically sized arrays, use the make() function. The make() function allocates a zeroed array and returns a slice that refers to that array.


Simple declaration

var s []int

does not allocate memory and s points to nil, while

s := make([]int, 0)

allocates memory and s points to memory to a slice with 0 elements.

Usually, the first one is more idiomatic if you don't know the exact size of your use case.


In addition to fabriziom's answer, you can see more examples at "Go Slices: usage and internals", where a use for []int is mentioned:

Since the zero value of a slice (nil) acts like a zero-length slice, you can declare a slice variable and then append to it in a loop:

// Filter returns a new slice holding only
// the elements of s that satisfy f()
func Filter(s []int, fn func(int) bool) []int {
    var p []int // == nil
    for _, v := range s {
        if fn(v) {
            p = append(p, v)
        }
    }
    return p
}

It means that, to append to a slice, you don't have to allocate memory first: the nil slice p int[] is enough as a slice to add to.


Just found a difference. If you use

var list []MyObjects

and then you encode the output as JSON, you get null.

list := make([]MyObjects, 0)

results in [] as expected.


A bit more completel example (one more argument in .make()):

slice := make([]int, 2, 5)
fmt.Printf("length:  %d - capacity %d - content:  %d", len(slice), cap(slice), slice)

Out:

length:  2 - capacity 5 - content:  [0 0]

Or with a dynamic type of slice:

slice := make([]interface{}, 2, 5)
fmt.Printf("length:  %d - capacity %d - content:  %d", len(slice), cap(slice), slice)

Out:

length:  2 - capacity 5 - content:  [<nil> <nil>]