Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch on reflect.Type?

Tags:

reflection

go

I have managed to do this, but it does not look efficient:

var t reflect.Type
switch t {
case reflect.TypeOf(([]uint8)(nil)):
    // handle []uint8 array type
}
like image 342
Sergei G Avatar asked Oct 30 '15 19:10

Sergei G


People also ask

What is reflect in go?

Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose. Reflection is often termed as a method of metaprogramming.

What is reflect indirect?

The reflect. Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.

What is reflect value?

The reflect. ValueOf() Function in Golang is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program.


2 Answers

First question, are you sure you want to switch on reflect.Type and not use a type switch? Example:

switch x := y.(type) {
case []uint8:
  // x is now a []uint8
}

Assuming that will not work for your situation, my recommendation is to make those package variables. Example:

var uint8SliceType = reflect.TypeOf(([]uint8)(nil))

func Foo() {
    var t reflect.Type
    switch t {
    case uint8SliceType:
        // handle []uint8 array type
    }

}
like image 110
Stephen Weinberg Avatar answered Nov 03 '22 13:11

Stephen Weinberg


you may not need reflect if you are just trying to detect type.

switch t := myVar.(type){
  case []uint8:
    // t is []uint8
  case *Foo:
    // t is *Foo
  default:
    panic("unknown type")
}

What are you actually trying to accomplish?

like image 38
captncraig Avatar answered Nov 03 '22 13:11

captncraig