我正在编写一个函数,旨在接受go中的字符串或切片。但是,当我键入参数时,interface{}
即使在检查类型的条件条件中也无法对这些变量执行操作。
编译器能否推断出我的局部变量Slice
在if
块内必须是类型的?在我确定这是片之后,如何完成for
循环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")
}
使用类型断言,例如
keySlice := keys.([]interface{})
valSlice := values.([]interface{})
并从那时起与他们合作。您甚至可以取消使用reflect
,例如:
keySlice, keysIsSlice := keys.([]interface{})
valSlice, valuesIsSlice := values.([]interface{})
if (keysIsSlice && valuesIsSlice) {
// work with keySlice, valSlice
return
}
keyString, keysIsString := keys.(string)
valString, valuesIsString := values.(string)
if (keysIsString && valuesIsString) {
// work with keyString, valString
return
}
return errors.New("types don't match")
或者,您可以将整个结构构造为类型开关:
switch k := keys.(type) {
case []interface{}:
switch v := values.(type) {
case []interface{}:
// work with k and v as slices
default:
// mismatch error
}
case string:
switch v := values.(type) {
case string:
// work with k and v as strings
default:
// mismatch error
}
default:
// unknown types error
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句