Home
Go
nil (Cannot Use nil as Type)
Updated May 31, 2023
Dot Net Perls
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.
Slice
interface
if
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen