I'm writing a function that is meant to accept either strings or slices in go. However, when I type my parameters as interface{}
I can't perform actions upon those variables even when inside a conditional which checks the type.
Can the compiler deduce that my local variable must be of type Slice
once inside my if
block? How can I accomplish a for
loop over the Slice
after I know for certain it is a Slice?
func createFields(keys interface{}, values interface{}) ([]map[string]interface{}, error) {
fields := make([]map[string]interface{}, 1, 1)
if reflect.TypeOf(keys).Kind() == reflect.Slice && reflect.TypeOf(values).Kind() == reflect.Slice {
if len(keys.([]interface{})) != len(values.([]interface{})) {
return fields, errors.New("The number of keys and values must match")
}
// How can I loop over this slice inside the if block?
for i, key := range keys.([]interface{}) {
item := map[string]string{
"fieldID": keys[i], // ERROR: invalid operation: keys[i] (type interface {} does not support indexing)
"fieldValue": values[i],
}
fields.append(item)// ERROR: fields.append undefined (type []map[string]interface {} has no field or method append)
}
return fields, _
}
if reflect.TypeOf(keys).Kind() == reflect.String && reflect.Typeof(values).Kind() == reflect.String {
item := map[string]string{
"fieldID": keys,
"fieldValue": values,
}
fields.append(item)
return fields, _
}
return fields, errors.New("Parameter types did not match")
}