Int*_*ter -1 reflection types go
我需要创建 StructField,其中需要传递 Type 字段的reflect.Type 值。我想将其他类型(如reflect.Bool、reflect.Int)传递给将在StructField 构造中使用的函数。我无法使用下面的代码执行此操作
reflect.StructField{
Name: strings.Title(v.Name),
Type: reflect.Type(reflect.String),
Tag: reflect.StructTag(fmt.Sprintf(`xml:"%v,attr"`, v.Name)),
}
Run Code Online (Sandbox Code Playgroud)
因为它
Cannot convert an expression of the type 'Kind' to the type 'Type'
Run Code Online (Sandbox Code Playgroud)
我将如何实现它?
reflect.Type是一种类型,所以表达式
reflect.Type(reflect.String)
Run Code Online (Sandbox Code Playgroud)
将是类型转换。类型reflect.String是reflect.Kindwhich没有实现接口类型reflect.Type,所以转换无效。
reflect.Type代表的值为string:
reflect.TypeOf("")
Run Code Online (Sandbox Code Playgroud)
一般来说,如果有一个值,reflect.Type任何(非接口)类型的描述符都可以使用该函数获取:reflect.TypeOf()
var x int64
t := reflect.TypeOf(x) // Type descriptor of the type int64
Run Code Online (Sandbox Code Playgroud)
如果你没有价值,这也是可能的。从类型化nil指针值开始,并调用Type.Elem()以获取指向的类型:
t := reflect.TypeOf((*int64)(nil)).Elem() // Type descriptor of type int64
t2 := reflect.TypeOf((*io.Reader)(nil)).Elem() // Type descriptor of io.Reader
Run Code Online (Sandbox Code Playgroud)