如何将类型值传递给类型为 reflect.Type 的变量 Golang
How to pass type value to a variable with the type reflect.Type Golang
我需要创建 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)),
}
因为它
Cannot convert an expression of the type 'Kind' to the type 'Type'
我将如何完成它?
reflect.Type
是一种类型,所以表达式
reflect.Type(reflect.String)
将是一个类型 conversion. Type of reflect.String
is reflect.Kind
,它没有实现接口类型 reflect.Type
,因此转换无效。
代表string
的reflect.Type
值为:
reflect.TypeOf("")
通常,任何(非接口)类型的 reflect.Type
描述符都可以使用 reflect.TypeOf()
函数获取,如果您有它的值:
var x int64
t := reflect.TypeOf(x) // Type descriptor of the type int64
没有值也是可以的。从类型化的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
我需要创建 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)),
}
因为它
Cannot convert an expression of the type 'Kind' to the type 'Type'
我将如何完成它?
reflect.Type
是一种类型,所以表达式
reflect.Type(reflect.String)
将是一个类型 conversion. Type of reflect.String
is reflect.Kind
,它没有实现接口类型 reflect.Type
,因此转换无效。
代表string
的reflect.Type
值为:
reflect.TypeOf("")
通常,任何(非接口)类型的 reflect.Type
描述符都可以使用 reflect.TypeOf()
函数获取,如果您有它的值:
var x int64
t := reflect.TypeOf(x) // Type descriptor of the type int64
没有值也是可以的。从类型化的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