Zero value in Golang
Last Updated :
09 Aug, 2019
In Go language, whenever we allocate memory for a variable with the help of declaration or by using new and if the variable is not initialized explicitly, then the value of such types of variables are automatically initialized with their zero value. The initialization of the zero value is done recursively. So, every element of the array of the structs has its fields zero if they are not specified with any value. Following are the zero values for different types of variables:
Type |
Zero Value |
Integer |
0 |
Floating point |
0.0 |
Boolean |
false |
String |
“” |
Pointer |
nil |
Interface |
nil |
Slice |
nil |
Map |
nil |
Channel |
nil |
Function |
nil |
Example 1:
package main
import "fmt"
func main() {
var q1 int
var q2 float64
var q3 bool
var q4 string
var q5 [] int
var q6 * int
var q7 map[ int ]string
fmt.Println( "Zero value for integer types: " , q1)
fmt.Println( "Zero value for float64 types: " , q2)
fmt.Println( "Zero value for boolean types: " , q3)
fmt.Println( "Zero value for string types: " , q4)
fmt.Println( "Zero value for slice types: " , q5)
fmt.Println( "Zero value for pointer types: " , q6)
fmt.Println( "Zero value for map types: " , q7)
}
|
Output:
Zero value for integer types: 0
Zero value for float64 types: 0
Zero value for boolean types: false
Zero value for string types:
Zero value for slice types: []
Zero value for pointer types: <nil>
Zero value for map types: map[]
Example 2:
package main
import "fmt"
func main() {
var q1 int = 2
var q2 float64
var q3 bool
var q4 string
var q5 [] int
var q6 * int
var q7 map[ int ]string
if q1 == 0 {
fmt.Println( "True" )
} else {
fmt.Println( "False" )
}
if q2 == 0 {
fmt.Println( "True" )
} else {
fmt.Println( "False" )
}
if q3 == false {
fmt.Println( "True" )
} else {
fmt.Println( "False" )
}
if q4 == "" {
fmt.Println( "True" )
} else {
fmt.Println( "False" )
}
if q5 == nil {
fmt.Println( "True" )
} else {
fmt.Println( "False" )
}
if q6 == nil {
fmt.Println( "True" )
} else {
fmt.Println( "False" )
}
if q7 == nil {
fmt.Println( "True" )
} else {
fmt.Println( "False" )
}
}
|
Output:
False
True
True
True
True
True
True
Share your thoughts in the comments
Please Login to comment...