Home »
Golang »
Golang Reference
Golang nil Variable with Examples
Golang | nil Variable: Here, we are going to learn about the nil variable with examples.
Submitted by IncludeHelp, on October 13, 2021 [Last updated : March 15, 2023]
nil Variable
In the Go programming language, nil is a predeclared identifier representing the zero value for many types such as a pointer, channel, func, interface, map, or slice type.
Syntax
var nil Type
Parameter(s)
Return Value
None
Example 1
// Golang program to demonstrate the
// example of nil variable
package main
import (
"fmt"
)
func main() {
// Declaring variables of different types
// and assigning them with nil values
a := (*struct{})(nil)
b := []int(nil)
c := map[int]bool(nil)
d := chan string(nil)
e := interface{}(nil)
// Printing the types and values
fmt.Printf("a: %T, %v\n", a, a)
fmt.Printf("b: %T, %v\n", b, b)
fmt.Printf("c: %T, %v\n", c, c)
fmt.Printf("d: %T, %v\n", d, d)
fmt.Printf("e: %T, %v\n", e, e)
}
Output
a: *struct {}, <nil>
b: []int, []
c: map[int]bool, map[]
d: chan string, <nil>
e: <nil>, <nil>
Example 2
// Golang program to demonstrate the
// example of nil variable
package main
import (
"fmt"
)
func main() {
// Comparing the type's
// default values with nil
fmt.Println(*new(*int) == nil)
fmt.Println(*new([]int) == nil)
fmt.Println(*new(map[int]bool) == nil)
fmt.Println(*new(chan string) == nil)
fmt.Println(*new(func()) == nil)
fmt.Println(*new(interface{}) == nil)
}
Output
true
true
true
true
true
true
Golang builtin Package »