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; iThis 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3