In Go we use the constant nil
instead of null
. This means "nothing exists." A slice can be uninitialized, and in this state it is nil
. We must be careful with nil
things.
Unlike in many languages, we cannot use nil
in place of a string
. Nil is not allowed in string
typed collections. An empty string
may be used instead.
Let us consider this example Go program. When we use the "var
" keyword, we declare variables. But these variables are not initialized when created.
interface
) is at first uninitialized. It is nil
. We can test for uninitialized things with nil
.package main import "fmt" func main() { // This is an uninitialized slice. var temp []int // The uninitialized slice is nil. if temp == nil { fmt.Println("Uninitialized slice is nil") } }Uninitialized slice is nil
String
errorThis program shows the error when trying to use nil
in a string
slice. Here we could use an empty string
to mean "no value."
nil
in a slice or array of strings. The nil
constant has no type—so it cannot substitute for a string
.package main func main() { temp := []string{} temp = append(temp, nil) }# command-line-arguments C:\programs\file.go:8: cannot use nil as type string in append
It is useful to research each programming concept until you understand it. In Go we find that slices can be left uninitialized, and these equal nil
.
With nil
we can test for uninitialized (or nonexistent) things. A slice variable that has not been assigned yet is nil
.