Ho provato a identificare una struttura con valore stringa (nome). reflect.TypeOf
restituisce Type
.asserzione tipo golang usando reflect.Typeof()
Tuttavia, l'asserzione di tipo deve essere type
.
Come posso trasmettere Type
a type
?
O qualche suggerimento per gestirlo?
http://play.golang.org/p/3PJG3YxIyf
package main
import (
"fmt"
"reflect"
)
type Article struct {
Id int64 `json:"id"`
Title string `json:"title",sql:"size:255"`
Content string `json:"content"`
}
func IdentifyItemType(name string) interface{} {
var item interface{}
switch name {
default:
item = Article{}
}
return item
}
func main() {
i := IdentifyItemType("name")
item := i.(Article)
fmt.Printf("Hello, item : %v\n", item)
item2 := i.(reflect.TypeOf(i)) // reflect.TypeOf(i) is not a type
fmt.Printf("Hello, item2 : %v\n", item2)
}
Questo è completamente impossibile in Go.Un'asserzione di tipo asserisce solo un tipo statico fisso con costante di tempo di compilazione. Devi rielaborare la tua soluzione. – Volker
Grazie per il commento. È molto chiaro! – dorajistyle