简体   繁体   中英

In Go, what's the inverse of reflect.SliceOf()?

In Go, reflect.SliceOf() makes a Type representing a slice of the given Type:

SliceOf returns the slice type with element type t. For example, if t represents int, SliceOf(t) represents []int.

However, I already have a Type for []int but want to get a Type for int . Is there an easy way to do that? (Note, I'm using int as an example. In reality, all I know is I have a slice, and I need to find what Type each element of the slice is.)

I'm trying to populate a slice of bool, int, float, or string, from a []string using reflection... here's the relevant piece:

numElems := len(req.Form["keyName"])
if structField.Kind() == reflect.Slice && numElems > 0 {
    slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
    for i := 0; i < numElems; i++ {
        // I have some other code here to fill out the slice
    }
}

But in order to fill out the slice, I need to know the type of the slice I'm filling out...

In your case, you already have the element type: structField.Type() . You can use reflect.New(t).Elem() to get an "editable" reflect.Value of a type. Once you've populated that value, you can call slice.Index(i).Set(...) to assign that value into the resulting slice.

To answer the letter of your question though, if you do have a slice and need to populate it, say you have a reflect.Type of a []int , then you can call .Elem() to get the reflect.Type for int .

See the Type documentation for the methods you can call on a Type.

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