The Initial Value nil
In the previous section, we mentioned that it is an erroneous behavior to assign an element to a nil
map.
Let's take this opportunity to explore the true meaning of nil
in Go.
The essence of nil
is a pre-declared identifier.
For basic data types, their initial values are different:
- Boolean values
- Numeric values
- Strings
However, for slices, dictionaries, pointers, channels, and functions, their initial value is nil
. It is not the initial default value that we are familiar with.
This is reflected in the instantiation objects that are assigned nil
. Although they can be printed, they cannot be used.
In addition, there are some points to note about nil
.
Incomparability of Different Types of nil
package main
import "fmt"
func main() {
var m map[int]string
var p *int
fmt.Printf("%v", m == p)
}
The program output is as follows:
invalid operation: m == p (mismatched types map[int]string and *int)
That is, we cannot compare the nil
of an int
type pointer with the nil
of a map.
They are not comparable.
nil
is not a keyword
package main
import "fmt"
func main() {
var nilValue = "= =$"
fmt.Println(nilValue)
}
The program output is as follows:
= =$
We can define a variable named nil
and it can be compiled without errors. However, we strongly recommend that you do not do this in actual development.
Incomparability of nil
package main
import "fmt"
func main() {
fmt.Println(nil == nil)
}
The program output is as follows:
invalid operation: nil == nil (operator == not defined on nil)