简体   繁体   中英

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. I would like to pass other types like reflect.Bool, reflect.Int to function which will be used in the construction of 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.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.

The reflect.Type value representing string is:

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:

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 :

t := reflect.TypeOf((*int64)(nil)).Elem()      // Type descriptor of type int64

t2 := reflect.TypeOf((*io.Reader)(nil)).Elem() // Type descriptor of io.Reader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM