On Tue, Jan 19, 2021 at 10:37 PM Ian Lance Taylor <[email protected]> wrote:
>
> On Tue, Jan 19, 2021 at 8:02 PM burak serdar <[email protected]> wrote:
> >
> > On Tue, Jan 19, 2021 at 8:38 PM Ian Lance Taylor <[email protected]> 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)
> > > }
> > > }
> > >
> >
> > But that breaks the generic function for non-interface types.
> >
> > type Str string
> >
> > func (s Str) String() string {return string(s)}
> >
> > func main() {
> > P(Str(""))
> > }
> >
> > Now the passed parameter is the zero value, but not nil.
>
>
> OK, but what are you really trying to check? Why do you want to check
> that an interface is not the zero value while at the same time you
> don't care whether a string is the zero value?
As a generic-function writer, I do not know if the argument will be an
interface or a concrete type. I don't want to check if it is
zero-value, I want to check if it is nil, because I don't want it to
panic.
If I was to convert the following non-generic function to a generic one:
func f(x SomeIntf) {
if x!=nil {
x.Something()
}
...
}
the obvious way to do this is:
func f[T SomeIntf](x T) {
...
}
but I can no longer check if x is nil.
Treating nil-checks as a special case might work maybe?
>
> 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/CAMV2RqqGVm%3DbiiAeKGHe5G%2By3WgZBSJGtbpA0ugZKngcW0Mgpw%40mail.gmail.com.