dongyingming8970 2019-07-08 16:30
浏览 81
已采纳

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

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")
}
  • 写回答

1条回答 默认 最新

  • duanguan1573 2019-07-08 16:39
    关注

    Use type assertions like

    keySlice := keys.([]interface{})
    valSlice := values.([]interface{})
    

    and work with those from that point onwards. You can even eliminate the use of reflect, like:

    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")
    

    Or you can structure the whole thing as type switches:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog