Generic zero value for compiler optimization

179 views
Skip to first unread message

Diego Augusto Molina

unread,
Aug 14, 2023, 9:52:48 AM8/14/23
to golang-nuts
Hi, thank you for reading. Whenever I need to use a zero value for a generic type in a func I do something like the following:

<code>
func SetZero[T any](pt *T) T {
    var zeroT T
    *pt = zeroT
}
</code>

That's all good, but I wonder how, if possible, it could be proved to the compiler that zeroT is the zero value for T. That would be to enable memclr optimization when bulk setting slice or array values to the zero value of their element type. Currently, as of 1.21, this only works when the src is a constant holding the zero value of the type. I also tried with something like *new(T), and it doesn't work either. But proving that the expression *new(T) in the src is the zero value for the type could potentially be easier than checking back if a certain variable (e.g. zeroT in the example) hasn't yet been reassigned or initialized to a non-zero value.
Also, as there's no guarantee of what would T could hold, it could use memclrHasPointers if that makes sense, which seems like a fare tradeoff at least for now if we want to play with slices with generic element type.
For reference, this is the code I'm trying:

<code>
package main
// file generic_slice_element_type_memclr.go

func clear[T any](s []T) {
for i := range s {
s[i] = *new(T)
}
}

func main() {
clear([]int{1, 2, 3})
}
</code>

And I'm compiling it with:

<code>
$ go version
go version go1.21.0 darwin/amd64
$ go tool compile -S generic_slice_element_type_memclr.go
...
</code>

Kind regards.

Axel Wagner

unread,
Aug 14, 2023, 12:57:35 PM8/14/23
to Diego Augusto Molina, golang-nuts

--
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 golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/b8ec1335-911c-42ed-96ce-a4b50153b8c9n%40googlegroups.com.

Diego Augusto Molina

unread,
Aug 14, 2023, 8:31:16 PM8/14/23
to golang-nuts
Thank you very much, that's actually what I was looking for.

Keith Randall

unread,
Aug 15, 2023, 12:37:51 PM8/15/23
to golang-nuts
It would be nice if the compiler could figure this out (both for *new(T) and zeroT).
When 61372 is implemented it will certainly be easier to just detect the zero builtin. Perhaps we should just wait for that.

Reply all
Reply to author
Forward
0 new messages