Home > Backend Development > Golang > How to Handle Default Values for Generic Types in Go?

How to Handle Default Values for Generic Types in Go?

DDD
Release: 2024-12-23 03:46:10
Original
170 people have browsed it

How to Handle Default Values for Generic Types in Go?

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:

  • Nil for pointers and slices
  • Empty string for strings
  • 0 for integers and floats

To return the zero value, declare a variable of type T and return it:

func getZero[T any]() T {
    var result T
    return result
}
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template