Type switch on generic parameter

272 views
Skip to first unread message

Matt Rosencrantz

unread,
Aug 11, 2022, 7:40:17 PM8/11/22
to golang-nuts
I'd really love to be able to do:

type allowedTypes{
  int64|float64|string
}

func Foo[T allowedTypes](arg T) {
    switch t := arg {
       case int64:
           // something
       case string:
          // something completely different
   }
}

As a way of having the type checker disallow other types from being passed so I don't have to return an error for incorrect types.  I guess this would be the same as asking for typesets to be allowed in normal interfaces like:

func Foo(arg allowedTypes) {...}

Is there another way to achieve this? Is there a reason it is not possible?
Thanks!
Matt



David Finkel

unread,
Aug 11, 2022, 7:51:43 PM8/11/22
to Matt Rosencrantz, golang-nuts
The type-parameters proposal discusses this a little.
You can cast your arg to an interface-type before type-asserting.
Note that the design uses the interface{} syntax, while you can now use "any" when converting to an interface.

Worth noting: you'll still have a runtime cost to the type-switch.
 
Thanks!
Matt



--
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/870bc9bd-2fcf-4598-9287-2da7adbc524an%40googlegroups.com.

roger peppe

unread,
Aug 12, 2022, 4:31:12 AM8/12/22
to Matt Rosencrantz, golang-nuts
See https://github.com/golang/go/issues/45380 for a proposal for a language feature that would allow this. In the meantime, you can convert to any, and type switch on that:

func Foo[T allowedTypes](arg T) {
    switch t := any(arg).(type) {
    case int64:
...


Reply all
Reply to author
Forward
0 new messages