generics: Zero value for any type parameter

162 views
Skip to first unread message

Johan Bolmsjö

unread,
Dec 16, 2021, 5:40:09 PM12/16/21
to golang-nuts

Hello,

I've been playing with the new generics support in 1.18beta 1 today. I've come across a situation a couple of times where it would be convenient to be able to conjure the zero value for a variable corresponding to a type parameter.

I've searched a bit for this to no avail. Understandably there is not much information on this topic in the wild yet. I've found a couple of issues in the issue tracker like returning '_' to represent the zero value but this does not seem to be implemented.

My workaround has been to create a dummy variable, zeroValue in the following example. I'm wondering if this is how to solve this problem or if there is a better way.

// Remove mapping associated with key from tree. Returns the removed value and
// true or the zero value of V and false if there was no mapping.
func (tree *Tree[K, V]) Remove(key K) (V, bool) {
        var zeroValue V
        if tree.root == nil {
                return zeroValue, false
        }
    ...
}

Johan Bolmsjö

unread,
Dec 16, 2021, 6:01:13 PM12/16/21
to golang-nuts
torsdag 16 december 2021 kl. 23:40:09 UTC+1 skrev Johan Bolmsjö:

My workaround has been to create a dummy variable, zeroValue in the following example. I'm wondering if this is how to solve this problem or if there is a better way.


I  realized I should have read the generics proposal before asking this question. My current workaround is mentioned together with some possible future improvements. At the time it seems to be idiomatic code. Sorry for the noise.
 
Reply all
Reply to author
Forward
0 new messages