我想取回我保存过的值的类型。我使用了reflect.Typeof()并保存了类型。然后尝试使用switch类型。类型将始终为"*reflect.rtype“。我不能通过类型断言来检索它们。
package main
import (
"fmt"
"reflect"
)
func main() {
var alltypes []interface{}
alltypes = append(alltypes, reflect.TypeOf(true))
alltypes = append(alltypes, reflect.TypeOf(0.0))
alltypes = append(alltypes, reflect.TypeOf(0))
fmt.Printf("%T\t%q\n", alltypes, alltypes)
for _, v := range alltypes {
fmt.Printf("%T\t%q\n", v, v)
res, ok := v.(bool)
fmt.Println("res: ", res, " ok: ", ok)
switch v.(type) {
default:
fmt.Printf("unexpected type %T\n", v)
case bool:
fmt.Println("bool type!")
case int:
fmt.Println("int type!")
case float64:
fmt.Println("float64 type!")
}
}
}发布于 2019-05-06 04:12:50
reflect.Type不包含您可以type assert的值(实际上您可以,但这只能是reflect.Type,而不是您想要的)。reflect.Type只是一个类型描述符(从一个值中获得)。
但是,您可以创建一个由reflect.Type表示的类型的值,并且可以对最初需要的值进行类型断言。
要创建新的指针值,请使用reflect.New()。要获得指定的值,请使用Value.Elem()。这些都封装在一个reflect.Value中。要将其解包,请使用Value.Interface()。
例如:
for _, v := range alltypes {
fmt.Printf("%T\t%q\n", v, v)
value := reflect.New(v.(reflect.Type)).Elem().Interface()
switch value.(type) {
default:
fmt.Printf("unexpected type %T\n", v)
case bool:
fmt.Println("bool type!")
case int:
fmt.Println("int type!")
case float64:
fmt.Println("float64 type!")
}
}这将输出(在Go Playground上试用):
[]interface {} ["bool" "float64" "int"]
*reflect.rtype "bool"
bool type!
*reflect.rtype "float64"
float64 type!
*reflect.rtype "int"
int type!另外,如果您不想创建新值,只需测试该类型,“保存”您感兴趣的类型的reflect.Type描述符,并对该类型使用普通的switch:
var (
TypeBool = reflect.TypeOf(true)
TypeFloat64 = reflect.TypeOf(0.0)
TypeInt = reflect.TypeOf(0)
)
func main() {
var alltypes []interface{}
alltypes = append(alltypes, reflect.TypeOf(true))
alltypes = append(alltypes, reflect.TypeOf(0.0))
alltypes = append(alltypes, reflect.TypeOf(0))
fmt.Printf("%T\t%q\n", alltypes, alltypes)
for _, v := range alltypes {
fmt.Printf("%T\t%q\n", v, v)
switch v {
default:
fmt.Printf("unexpected type %T\n", v)
case TypeBool:
fmt.Println("bool type!")
case TypeInt:
fmt.Println("int type!")
case TypeFloat64:
fmt.Println("float64 type!")
}
}
}这将输出(在Go Playground上试用):
[]interface {} ["bool" "float64" "int"]
*reflect.rtype "bool"
bool type!
*reflect.rtype "float64"
float64 type!
*reflect.rtype "int"
int type!发布于 2019-05-06 04:18:06
根据您想要做什么,您不一定需要使用类型断言来执行此操作。v.(reflect.Type).Kind()会告诉你它的类型(例如,reflect.Bool、reflect.Float64、reflect.Int等)。
https://stackoverflow.com/questions/55995917
复制相似问题