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.
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.
nil
can represent zero values for several types like pointer types, map types, slice types, function types, channel types, interface types, and so on.
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
andfalse
are bool types.
package mainimport ("fmt")func main() {n := nilfmt.Println(n)}
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 mainimport ("fmt")func main() {var n*int = nilfmt.Println(n)}
n
an int
type and then make it equal to nil
.n
.nil
can be reassignedThe pre-declared nil
keyword can be shadowed by declaring it again.
The following code explains it better:
package mainimport "fmt"func main() {nil := 12fmt.Println(nil) // It will print 12//The following wont compilevar _ map[string]int = nil}
12
, to the pre-declared nil
nil
.nil
gets shadowed using nil
(type int
) as the map[string]int
type in the assignment.Free Resources