skip to content
Alvin Lucillo

Zero value with generics

/ 1 min read

Generics can also help determine the zero value of the current concrete type. In the example below, Zero is a generic function takes a value of any type and declares zero as type T, the type of the current value passed to the function. The type of value is inferred from T.

The result shows the default/zero values for integer, string, and pointer types. However, for collection types like map and slice, Printf doesn’t show nil because it shows readable format for those types or their collection representation, but we can see from the output that they have nil zero value.

func Zero[T any](v T) T {
	var zero T
	return zero
}
func main() {
	fmt.Printf("'%v'\n", Zero(1))
	fmt.Printf("'%v'\n", Zero("hello"))
	var v *string
	fmt.Printf("'%v'\n", Zero(v))
	var m map[string]string
	fmt.Printf("'%v' isnil=%v\n", Zero(m), Zero(m) == nil)
	fmt.Printf("'%v' isnil=%v\n", Zero([]int{}), Zero([]int{}) == nil)

}
go run .
'0'
''
'<nil>'
'map[]' isnil=true
'[]' isnil=true