195 words
1 minutes
Zero Values in Golang
In Go, when variables are declared but not explicitly initialized, they are assigned their zero value according to their type. The zero value is a default value that depends on the data type. Here are the zero values for some common data types in Go:
- Numeric types (int, float64, etc.): 0
- Boolean type: false
- String type: ""
- Pointers, slices, maps, channels, functions, and interfaces: nil
Here is an example demonstrating zero values for various types:
package main
import "fmt"
func main() {
// Numeric types
var num int
var floatNum float64
fmt.Println("Integer zero value:", num) // Output: 0
fmt.Println("Float zero value:", floatNum) // Output: 0
// Boolean type
var boolean bool
fmt.Println("Boolean zero value:", boolean) // Output: false
// String type
var str string
fmt.Println("String zero value:", str) // Output: ""
// Pointers, slices, maps, channels, functions, and interfaces
var pointer *int
var slice []int
var mp map[string]int
var ch chan int
var fn func()
var iface interface{}
fmt.Println("Pointer zero value:", pointer) // Output: <nil>
fmt.Println("Slice zero value:", slice) // Output: []
fmt.Println("Map zero value:", mp) // Output: map[]
fmt.Println("Channel zero value:", ch) // Output: <nil>
fmt.Println("Function zero value:", fn) // Output: <nil>
fmt.Println("Interface zero value:", iface) // Output: <nil>
}
Zero Values in Golang
https://rabisiddique.com/posts/zero-values-in-go/Author
Rabi Siddique
Published at
2024-02-13