patterngoCritical
Declare slice or make slice?
Viewed 0 times
makeslicedeclare
Problem
In Go, what is the difference between
I find that both works, but which one is better?
var s []int and s := make([]int, 0)?I find that both works, but which one is better?
Solution
In addition to fabriziom's answer, you can see more examples at "Go Slices: usage and internals", where a use for
Since the zero value of a slice (
It means that, to append to a slice, you don't have to allocate memory first: the
[]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.Code Snippets
// 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
}Context
Stack Overflow Q#25543520, score: 115
Revisions (0)
No revisions yet.