[英]Reverse of reflect.TypeOf
我想找回我保存一次的值的類型。 我使用了reflect.Typeof()並保存了類型。 然后嘗試使用開關類型。 該類型將始終為“ * 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!")
}
}
}
一個reflect.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!
推薦讀物: 圍棋博客:反思法則
根據您要執行的操作,您不一定需要使用類型斷言來執行此操作。 v.(reflect.Type).Kind()
將告訴您它是哪種類型(例如, reflect.Bool
, reflect.Float64
, reflect.Int
等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.