[generics] use interfaces in type lists

90 views
Skip to first unread message

Davor Kapša

unread,
Jul 3, 2020, 12:46:10 PM7/3/20
to golang-nuts
Hi, 

Is it planned to combine type list with embed interfaces,
or it is too confusing ?

type numeric interface {
type integers, floats
}

type integers interface {
type int, int8, int16, int32, int64, unsigneds
}

type unsigneds interface {
type uint, uint8, uint16, uint32, uint64
}

type floats interface {
type float32, float64
}


Thanks for current draft, it feels very idiomatic to me.

--- Davor

Ian Lance Taylor

unread,
Jul 3, 2020, 3:06:14 PM7/3/20
to Davor Kapša, golang-nuts
Using an interface type in a type list has a defined meaning: the type
argument must have as its underlying type that interface type. It
doesn't mean what I think you want it to mean, which is to serve as a
union of the type lists of the interface types. What you suggest
would not be impossible, but it would mean making an exception to the
rules for type lists.

Ian

Steven Blenkinsop

unread,
Jul 3, 2020, 5:42:12 PM7/3/20
to Ian Lance Taylor, Davor Kapša, golang-nuts
On Fri, Jul 3, 2020 at 3:05 PM, Ian Lance Taylor <ia...@golang.org> wrote:

Using an interface type in a type list has a defined meaning: the type
argument must have as its underlying type that interface type.  It
doesn't mean what I think you want it to mean, which is to serve as a
union of the type lists of the interface types.  What you suggest
would not be impossible, but it would mean making an exception to the
rules for type lists.

One way to disambiguate would be to define a pseudo-type, I(T) for some interface type and type T which is identical to T if implements I, and is otherwise an empty type that doesn't match any other type. This could also solve the type switching on type parameters question, since 

switch t := t.(type) {
case interface { type int }(T):
   ...
}

would match for a value t of type T if the underlying type of T is int. The syntax is a bit unwieldy, but it makes it clear that we're matching based on the type-list semantics and disambiguates between matching to an interface type vs. matching to a concrete type that implements an interface. That it looks like a conversion shouldn't be too much of an issue, since generic functions are also to be followed by either a type list or a value list.

These pseudo-types would probably only make sense in type lists and type switches, just as null is only usable as a pseudo-type in type switches.

There might be cleaner ways of doing this, though.

Reply all
Reply to author
Forward
0 new messages