On Tue, Jan 19, 2021 at 8:41 PM Dan Kortschak <[email protected]> wrote: > > On Tue, 2021-01-19 at 19:38 -0800, Ian Lance Taylor wrote: > > On Tue, Jan 19, 2021 at 7:06 PM burak serdar <[email protected]> > > wrote: > > > > > > In the following program, it is valid to pass an interface to > > > function P: > > > > > > func P[T fmt.Stringer](x T) { > > > fmt.Println(x) > > > } > > > > > > func main() { > > > var v fmt.Stringer > > > P(v) > > > } > > > > > > However, there is no way for P to check if x is nil. This does not > > > compile: > > > > > > func P[T fmt.Stringer](x T) { > > > if x!=nil { > > > fmt.Println(x) > > > } > > > } > > > > > > Is it possible to write a generic function that can test if its > > > argument with a constraint is nil? > > > > For an interface type the value "nil" is the zero value of the type, > > so this is the general zero value issue mentioned at > > > https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md#the-zero-value > > > > You can write > > > > func P[T fmt.Stringer](x T) { > > var zero T > > if x!=zero { > > fmt.Println(x) > > } > > } > > > > Ian > > Would that work for non-comparable types? Say the T has an underlying > []int type, then the comparison is not against nil and you end up with > a panic.
Fair point. But I'm not sure what the goal is here. Perhaps if we can define that we can figure out how to make it work. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcV_Je%2BxtetNnRBmiSxHYcTt%3Du4NvxNTHdgEMf1YQ7GQDQ%40mail.gmail.com.
