Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang zero value for generic types [duplicate]

Tags:

generics

go

I'm testing version 1.18beta2 of golang. I have this function:


func Do[T any](value T) (T, bool) {
     if guardCondition {
         return nil, false // Complains about "cannot use nil as T value in return statement"
     }
     ... // rest of function
}

Which will not complile due to cannot use nil as T value in return statement . Normally, you would return a pointer or whichever "nilable" type. However, when using generics no type seems to please de compiler. I cannot find any online resource handling any kind of this example.

like image 376
sonirico Avatar asked Dec 31 '25 10:12

sonirico


1 Answers

You can create "zero" value using *new(T) it returns what you would expect.

You can play around with *new(T) here - https://go.dev/play/p/7e7zGKMgoRW.

More information - https://stackoverflow.com/a/70589302/4108803.

Original answer,

Well, just tried with

func Do[T any](value T) (T, bool) {
     if guardCondition {
         var noop T
         return noop, false
     }
     ... // rest of function
}

which makes the trick :)

like image 152
sonirico Avatar answered Jan 02 '26 05:01

sonirico