[generics] Zero value

231 views
Skip to first unread message

bruno...@gmail.com

unread,
Jun 18, 2020, 12:34:55 PM6/18/20
to golang-nuts
First, congratulations on the working compiler! Very cool to try out generics in Go.

I was experimenting with some simple generic functions and felt the need for the zero value of a generic type. I've read the discussion anticipated in your proposal, so I'd like to use this topic just to provide my sentiment, and perhaps gather it from others.

In my opinion, the most Go-like proposal is using '_' to signify the zero value in RHS. We are already used to having '_' in LHS to accept whatever type, and although the meaning is slightly changed (from 'whatever' to 'zero'), it's conceptually close.

I'm opposed to a change that uses '{}' or 'T{}' to mean zero type, as in this proposal, because in my mind curly braces are used for composite types. Imagining that 'T' is a placeholder, It's weird replacing 'T{}' for 'int{}', for example. I'm super in favor of having a leaner syntax for composite types, though 😁.

Whatever is decided, please don't punt on this issue and recommend '*new(T)'. That's really ugly and feels wrong to allocate and immediately dereference the value just to circumvent a syntax change. Even if the compiler is smart enough not to allocate anything, that's what's written in the source code.

Thanks.

Ivan Ivanyuk

unread,
Jun 19, 2020, 7:59:59 AM6/19/20
to golang-nuts
What about something like int.CreateZeroValue(), or T.CreateZeroValue() and CreateZeroValueInterface?

Max

unread,
Jun 22, 2020, 8:09:11 AM6/22/20
to golang-nuts
Types are not first-class in Go, thus T.someMethod() is somewhat an unusual syntax.

The proposal to use 'T{}' to mean zero value of T breaks Go compatibility promise:
if T is a map type or a slice type, 'T{}' already has a meaning:
create a non-nil, zero-elements map (or slice).
Instead the zero value of such types is nil.

Using '_' could be an elegant solution in places where type inference can deduce the correct type.

Two more ideas that I did not see yet are:
1. use 'T()' to mean zero value of T - currently does not compile, thus Go compatibility promise is preserved.
2. define a new compiler builtin 'zero(T)'

Andrew Werner

unread,
Jun 22, 2020, 9:13:43 AM6/22/20
to golang-nuts
In order to get a zero value, does the following work today? Is it acceptable?

func GenericFunc(type T)() T {
   
return func() (t T) { return t }()
}

This could also just be written like below but above I was trying to demonstrate how to make a zero value within another function.

func ZeroValue(type T)() (t T) {
   
return t
}

bruno...@gmail.com

unread,
Jun 22, 2020, 4:41:58 PM6/22/20
to golang-nuts
Yes, they work, though a simpler solution is using 'var zero T' before the return statement. It'd be nice to have it inline, specially for multiple return values.
Reply all
Reply to author
Forward
0 new messages