我試圖識別一個結構與字符串值(名稱)。 reflect.TypeOf
返回Type
。golang類型使用reflect.Typeof斷言()
但類型斷言需要type
。
如何鑄造Type
至type
?
或有任何建議來處理它?
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)
}
這在Go中是完全不可能的。類型斷言僅聲明編譯時常量固定的靜態類型。你必須重做你的解決方案。 – Volker
感謝您的評論。這很清楚! – dorajistyle