Generic array and slice type options

204 views
Skip to first unread message

Daniel Theophanes

unread,
Jan 8, 2023, 4:17:01 PM1/8/23
to golang-nuts
When playing around with generics, I ran into what I perceive as an odd limitation.

I forked an audio package "beep" to do some fun generics with it.

I was trying to use the following interfaces:

type Point[S Size] interface {
    // NOTE: Uncommenting the next line will result in errors.
   // [1]S | [2]S
   [2]S
}

type Size interface {
   float64 | float32
}

I was thinking I could change the internal data structure from float64 or float32. This part works. I was thinking I could change the internal data structure from one channel to two with [1]S | [2]S. Now I realize this probably isn't a great idea to begin with, but hear me out...

When I try to change to a union between len 1 array to len 2 array:
 1. I cannot compile any access to point[1] even if behind a len(point) guard.
 2. "for range point" appears to stop working at all, though I feel like it should still work, as it would work on either data type.

I fully get why this is probably not a good serious approach, but more then anything, could someone help me with the why of the compiler errors? The specific error is "(P has no core type)".

Thank you,
-Daniel

Ian Lance Taylor

unread,
Jan 8, 2023, 11:40:34 PM1/8/23
to Daniel Theophanes, golang-nuts
Well, that error is why. In the current spec and implementation,
certain operations are only available if the type parameter has a
"core type". See https://go.dev/ref/spec#Core_types . I believe that
over time we can move toward a more flexible spec and implementation
that doesn't rely on that concept, but doing that will require
defining the notion of a dependent type--a type that depends on a type
parameter.

Ian

Daniel Theophanes

unread,
Jan 9, 2023, 10:21:32 AM1/9/23
to Ian Lance Taylor, golang-nuts
Thank you Ian.
Reply all
Reply to author
Forward
0 new messages