golang zero value for generic types

Viewed 1643

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.

1 Answers

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 :)

Related