As a complement to @ANisus' answer ...
The following is some information from the book, "Go in Action," which I think is worth mentioning:
The difference between nil and empty slices
If we think about such a fragment:
[pointer] [length] [capacity]
then
nil slice: [nil][0][0] empty slice: [addr][0][0] // points to an address
nil slice
Theyre useful when you want to represent a fragment that does not exist, for example, when an exception occurs in a function that returns a slice.
// Create a nil slice of integers. var slice []int
empty fragment
Empty fragments are useful when you want to represent an empty collection, for example, when a database query returns null results.
// Use make to create an empty slice of integers. slice := make([]int, 0) // Use a slice literal to create an empty slice of integers. slice := []int{}
Regardless of whether you use a nil fragment or an empty fragment, the built-in functions append , len and cap work the same.
Go to the playground :
package main import ( "fmt" ) func main() { var nil_slice []int var empty_slice = []int{} fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice)) fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice)) }
prints:
true 0 0 false 0 0
tgogos Sep 01 '17 at 9:50 a.m. 2017-09-01 09:50
source share