What does nil mean in Golang?

What is Golang?

Golang, also known as Go, is an open-source, compiled, and statically-typed programming language developed by Google. The language has a simple syntax and robust standard libraries.

It is used in real-world applications and supports imperative and OOP paradigms.

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.

Zero values for many types

nil can represent zero values for several types like pointer types, map types, slice types, function types, channel types, interface types, and so on.

Default type for nil

There is no default type for pre-defined nil. It is the only untyped value that does not have a default type.

Note: Default types define the variable and its type. For example, true and false are bool types.

Example

package main
import (
"fmt"
)
func main() {
n := nil
fmt.Println(n)
}
Testing if nil has a default type

The code above will not execute because there isn’t a type assigned to nil. Let’s try this code where we assign a type to nil:

package main
import (
"fmt"
)
func main() {
var n*int = nil
fmt.Println(n)
}
Implementing it by assigning a type to nil

Explanation

  • Line 8: We assign n an int type and then make it equal to nil.
  • Line 9: We print the assigned variable, n.

Pre-declared nil can be reassigned

The pre-declared nil keyword can be shadowed by declaring it again.

The following code explains it better:

package main
import "fmt"
func main() {
nil := 12
fmt.Println(nil) // It will print 12
//The following wont compile
var _ map[string]int = nil
}
Testing if nil can be shadowed

Explanation

  • Line 6: We assign the value, 12, to the pre-declared nil
  • Line 7: We print the assigned nil.
  • Line 10: This line doesn’t compile because nil gets shadowed using nil (type int) as the map[string]int type in the assignment.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved