Type Assertion Using reflect.TypeOf() in Go
In Go, when working with interfaces, it may be necessary to perform type assertion to obtain the underlying concrete type. The question arises regarding how to cast a Type (returned by reflect.TypeOf()) to a specific type for assertion.
Problem:
Consider the example code:
func IdentifyItemType(name string) interface{} { var item interface{} switch name { default: item = Article{} } return item }
Here, we aim to identify a struct (Article) based on a string name. However, type assertion requires a type, but reflect.TypeOf() returns a Type.
Solution:
If the goal is to switch on the type of the outer interface{}, reflection is not necessary:
switch x.(type){ case int: dosomething() }
However, to switch on the type of attributes within an interface, reflection can be employed:
s := reflect.ValueOf(x) for i:=0; i<s.NumValues; i++{ switch s.Field(i).Interface().(type){ case int: dosomething() } }
This allows the switching of types on the attributes of the interface. While not an elegant solution, it provides functionality until a better alternative is discovered.
The above is the detailed content of How Can I Perform Type Assertion on a Go `reflect.TypeOf()` Result?. For more information, please follow other related articles on the PHP Chinese website!