On Thu, Aug 11, 2022 at 7:40 PM 'Matt Rosencrantz' via golang-nuts <
golang-nuts@googlegroups.com> wrote:

> 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?
>

The type-parameters proposal discusses this a little.
You can cast your arg to an interface-type before type-asserting.
https://go.googlesource.com/proposal/+/HEAD/design/43651-type-parameters.md#identifying-the-matched-predeclared-type
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+unsubscr...@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
> <https://groups.google.com/d/msgid/golang-nuts/870bc9bd-2fcf-4598-9287-2da7adbc524an%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CANrC0Bh_bAL%2B_NH5YA1tvM8s4bDOJ3ug2veFOd3q2JjyKaLGdQ%40mail.gmail.com.

Reply via email to