nil (Cannot Use nil as Type)Use the nil keyword to test uninitialized slices. A string cannot be nil.
This page was last reviewed on May 31, 2023.
Nil. 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.
An example program. Let us consider this example Go program. When we use the "var" keyword, we declare variables. But these variables are not initialized when created.
And A slice (or 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 error. This program shows the error when trying to use nil in a string slice. Here we could use an empty string to mean "no value."
Important We cannot use 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
Some research. 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.
A review. With nil we can test for uninitialized (or nonexistent) things. A slice variable that has not been assigned yet is nil.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.