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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With