[英]How to pass type value to a variable with the type reflect.Type Golang
I need to create StructField, in which I need to pass reflect.Type value for the Type field.我需要创建 StructField,我需要在其中为 Type 字段传递 reflect.Type 值。 I would like to pass other types like reflect.Bool, reflect.Int to function which will be used in the construction of StructField.
我想将其他类型(如 reflect.Bool、reflect.Int)传递给 function,它们将用于构建 StructField。 I cannot do this with the code below
我不能用下面的代码做到这一点
reflect.StructField{
Name: strings.Title(v.Name),
Type: reflect.Type(reflect.String),
Tag: reflect.StructTag(fmt.Sprintf(`xml:"%v,attr"`, v.Name)),
}
Because it因为它
Cannot convert an expression of the type 'Kind' to the type 'Type'
How would I accomplish it?我将如何实现它?
reflect.Type
is a type, and so the expression reflect.Type
是一个类型,所以表达式
reflect.Type(reflect.String)
Would be a type conversion .将是类型转换。 Type of
reflect.String
is reflect.Kind
which does not implement the interface type reflect.Type
, so the conversion is invalid. reflect.Kind
reflect.String
没有实现接口类型reflect.Type
,所以转换无效。
The reflect.Type
value representing string
is:表示
string
的reflect.Type
值为:
reflect.TypeOf("")
Generally the reflect.Type
descriptor of any (non-interface) type can be acquired using the reflect.TypeOf()
function if you have a value of it:通常,可以使用
reflect.TypeOf()
function 获取任何(非接口)类型的reflect.Type
描述符,如果你有它的值:
var x int64
t := reflect.TypeOf(x) // Type descriptor of the type int64
It's also possible if you don't have a value.如果您没有价值,这也是可能的。 Start from a typed
nil
pointer value, and call Type.Elem()
to get the pointed type :从一个类型化的
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.