Default Value for Generic Types
Returning nil for any type is not allowed in Go. Even for generic types, where T could represent any type, nil is not a valid option. Types like structs and integers don't have a nil representation.
Instead, the zero value for the specific type argument used for T can be returned. The zero value varies depending on the type:
To return the zero value, declare a variable of type T and return it:
func getZero[T any]() T { var result T return result }
For example, using the getZero function:
i := getZero[int]() fmt.Printf("%T %v\n", i, i) // Output: int 0 s := getZero[string]() fmt.Printf("%T %q\n", s, s) // Output: string "" p := getZero[image.Point]() fmt.Printf("%T %v\n", p, p) // Output: image.Point (0,0) f := getZero[*float64]() fmt.Printf("%T %v\n", f, f) // Output: *float64 <nil>
The above is the detailed content of How to Handle Default Values for Generic Types in Go?. For more information, please follow other related articles on the PHP Chinese website!