I want to retrieve back the type of value I saved once. I used reflect.Typeof() and saved the type. then try to use switch type. the type will always be "*reflect.rtype ". I couldn't retrieve either by type assertion.
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!")
}
}
}
Playground: https://play.golang.org/p/kqDo4DPYjra
Aucun commentaire:
Enregistrer un commentaire