【发布时间】:2015-03-10 03:15:05
【问题描述】:
我尝试使用字符串值(名称)来识别结构。
reflect.TypeOf 返回Type。
但是类型断言需要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 中是完全不可能的。类型断言仅断言编译时常量固定静态类型。你必须重新设计你的解决方案。