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 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。