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:
// Go program to illustrate the concept of zero value package main import "fmt"
// Main Method func main() { // Creating variables
// of different types
var q1 int
var q2 float64
var q3 bool
var q4 string
var q5 [] int
var q6 * int
var q7 map[ int ]string
// Displaying the zero value
// of the above variables
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:
// Go program to check the variable // contains zero value or not package main import "fmt"
func main() { // Creating variables of different types
var q1 int = 2
var q2 float64
var q3 bool
var q4 string
// Slice
var q5 [] int
// Pointer
var q6 * int
// Map
var q7 map[ int ]string
// Checking if the given variables
// contain their zero value or not
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
Article Tags :