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
A string cannot be nil, because the data structure in go doesn't allow it. You can have a pointer to a byte array holding character representations in go be null, but that isn't a string.
An empty slice is a slice that is declared by using the built-in make function and it doesn't have nil as its zero value.
About nil. nil is a predefined identifier in Go that represents zero values of many types. nil is usually mistaken as null (or NULL) in other languages, but they are different. Note: nil can be used without declaring it.
Nil represents a zero value in Golang. As you may already know, zero values are the "default" value for defined variables in Go. This means that some types doesn't cannot hold empty values, instead acquiring zero values upon initialization to get rid of the problem of checking values for emptyness.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With