我正在编写一个函数,用于在 go 中接受字符串或 slice 。但是,当我将参数键入为 interface{}
时,即使在检查类型的条件中,我也无法对这些变量执行操作。
编译器能否在我的 if
block 中推断出我的局部变量必须是 Slice
类型?在确定 Slice
是一个 Slice 之后,如何完成 for
循环?
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
}
关于go - 如何为接受 interface{} 的函数创建类型条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56939128/