WithIndex
Returns a map with index-value pairs.
- Use
reflect.ValueOf()to get the array or slice,make()to create a newmap. - Use a
forloop withValue.Len(),Value.Index()andValue.Interface()to iterate over each element and add it to the map.
import "reflect"
func WithIndex(params ...interface{}) map[int]interface{} {
arr, m := reflect.ValueOf(params[0]),
make(map[int]interface{})
for i := 0; i < arr.Len(); i++ {
m[i] = arr.Index(i).Interface()
}
return m
}WithIndex([]int{4, 3, 2, 1}) // [0:4 1:3 2:2 3:1]