Reputation: 14824
I was looking at the Slice Tricks: https://github.com/golang/go/wiki/SliceTricks
and I noticed in their copy example they have []T(nil)
I haven't seen (nil)
like this before and I can't find any documentation on using it or what exactly it accomplishes (I know it's self explanatory but I want to know how it acts the same as make
or []string{}
the only reference I can find by googling "golang (nil) slice" is
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:
But it doesn't say where it can be used or exactly what it accomplishes, like can I use this with structs or whatever I want?
e.g.:
package main
import "log"
func main() {
str := []string{"Hello", "Bye", "Good Day", "????????"}
cop := append([]string(nil), str...)
log.Println(str)
log.Println(cop)
}
I'm strictly only curious about how (nil)
operates, and what it can operate on.
Like does
[]string(nil)
Operate the same as
[]string{}
or what is the difference here
Upvotes: 11
Views: 2614
Reputation: 109442
This is a type conversion, converting a nil
to a slice.
These are equivalent
var t []string
t := []string(nil)
In both cases, t
is of type []string
, and t == nil
Upvotes: 13
Reputation: 348
list := []string(nil) // list is an empty slice of strings
func append(slice []Type, elems ...Type) []Type
function takes a slice of strings and a variable length list of strings, and returns a slice where the list of strings is appended to the end.
so:
cop := append([]string(nil), str...)
will create an empty slice of strings and append the strings in "str" and return the result.
This the result slice is a copy, because it has all of the same values in the same order.
Upvotes: 1