如何为接受接口{}的函数创建类型条件?

时间:2019-07-08 16:30:36

标签: go

我正在编写一个函数,用于接受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")
}

1 个答案:

答案 0 :(得分:4)

使用类似类型的断言

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
}