Return default value for generic type


How do you return nil for a generic type T?

func (list *mylist[T]) pop() T {
    if list.first != nil {
        data :=
        list.first =
        return data
    return nil

func (list *mylist[T]) getfirst() T {
    if list.first != nil {
    return nil

I get the following compilation error:

 cannot use nil as T value in return statement


You can’t return nil for any type. If int is used as the type argument for T for example, returning nil makes no sense. nil is also not a valid value for structs.

What you may do–and what makes sense–is return the zero value for the type argument used for T. For example the zero value is nil for pointers, slices, it’s the empty string for string and 0 for integer and floating point numbers.

How to return the zero value? Simply declare a variable of type T, and return it:

func getZero[T any]() T {
    var result T
    return result

Testing it:

i := getZero[int]()
fmt.Printf("%T %v\n", i, i)

s := getZero[string]()
fmt.Printf("%T %q\n", s, s)

p := getZero[image.Point]()
fmt.Printf("%T %v\n", p, p)

f := getZero[*float64]()
fmt.Printf("%T %v\n", f, f)

Which outputs (try it on the Go Playground):

int 0
string ""
image.Point (0,0)
*float64 <nil>

Answered By – icza

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.