ADVERTISEMENT
ADVERTISEMENT

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

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):

  • None

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.