how to use type switch with reflect.Type?

352 views
Skip to first unread message

Jochen Voss

unread,
Jun 5, 2013, 5:27:28 AM6/5/13
to golan...@googlegroups.com
Dear all,

For a given variable, say x, a type switch can be used
to execute different commands depending on the
type of x as follows:

    switch value := x.(type) {
    case string:
      ...
    case session.CsrfToken:
      ...
    default:
      ...
    }

Now I came across a situation where the variable is
not given directly but instead is found via the introspection
facilities in the reflect module:

    var valueOfX reflect.Value
    ...
    typeOfX := x.Type()

I would like to use a type switch for this variable.
The best I came up with so far was

    switch valueOfX.Interface().(type) {
      ...
    }

Is there a better way to do this?  What if I only have
typeOfX?  For this case I could only think of

    switch reflect.New(typeOfX).Elem().Interface().(type) {
      ...
    }

which looks clumpsy!  Any better way of doing this?

Many thanks,
Jochen

buzzlight

unread,
Jun 5, 2013, 5:47:45 AM6/5/13
to golan...@googlegroups.com
Maybe 
switch typeOfX.Name  {
 ...
}


在 2013年6月5日星期三UTC+8下午5时27分28秒,Jochen Voss写道:

Rémy Oudompheng

unread,
Jun 5, 2013, 6:13:31 AM6/5/13
to Jochen Voss, golang-nuts
Use a value switch on typeOfX directly.

Rémy.


2013/6/5, Jochen Voss <joche...@gmail.com>:
> --
> 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.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

Jochen Voss

unread,
Jun 5, 2013, 4:43:05 PM6/5/13
to golan...@googlegroups.com, Jochen Voss
Dear Rémy,


On Wednesday, 5 June 2013 12:13:31 UTC+2, Rémy Oudompheng wrote:
Use a value switch on typeOfX directly. 

What would match typeOfX against.  Would the "case string"
from the original example the be converted into the following?

    case reflect.TypeOf(""):
      ...

Or is there a generic way to turn a type as used in a type switch
into a reflect.Type?

Many thanks,
Jochen

jimmy frasche

unread,
Jun 5, 2013, 4:52:24 PM6/5/13
to Jochen Voss, golang-nuts
I usually switch on typeOfX.Kind() if I want to check it against primitive types

http://golang.org/pkg/reflect/#Kind
Reply all
Reply to author
Forward
0 new messages