Note: Declare slice or make slice? does not answer my question because that compares slice declaration vs. make slice whereas my question compares slice literal vs. make slice. That question has an easy answer because a bare slice declaration creates a nil slice, however, if you read my question below carefully, I do not create a nil slice at all.
There are two ways to create a slice and append to it. My code below shows both ways as Example 1
and Example 2
.
package main
import (
"fmt"
)
func main() {
// Example 1
a := []int{}
fmt.Printf("len(a): %d; cap(a): %d; a: %v\n", len(a), cap(a), a)
a = append(a, 10, 20, 30, 40, 50)
fmt.Printf("len(a): %d; cap(a): %d; a: %v\n", len(a), cap(a), a)
// Example 2
b := make([]int, 0)
fmt.Printf("len(b): %d; cap(b): %d; b: %v\n", len(b), cap(b), b)
b = append(b, 10, 20, 30, 40, 50)
fmt.Printf("len(b): %d; cap(b): %d; b: %v\n", len(b), cap(b), b)
}
Output:
len(a): 0; cap(a): 0; a: []
len(a): 5; cap(a): 6; a: [10 20 30 40 50]
len(b): 0; cap(b): 0; b: []
len(b): 5; cap(b): 6; b: [10 20 30 40 50]
Are both ways of creating empty slice with []int{}
and make([]int, 0)
equivalent? Is there any situation where they make a difference in behavior?