首页 > 解决方案 > 类型断言非简约

问题描述

我有以下,它的工作原理:

        reflectItem := reflect.ValueOf(dataStruct)
        subItem := reflectItem.FieldByName(subItemKey)
        switch subItem.Interface().(type) {
            case string:
                subItemVal := subItem.Interface().(string)
                searchData = bson.D{{"data." + 
                  strings.ToLower(subItemKey), subItemVal}}
            case int64:
                subItemVal := subItem.Interface().(int64)
                searchData = bson.D{{"data." + 
                  strings.ToLower(subItemKey), subItemVal}}
        }

问题是这似乎非常不吝啬。我非常想简单地获得类型,subItem而没有 switch 语句,该语句在按名称找到字段后简单地断言自己的类型。但是,我不确定如何支持这一点。想法?

标签: objectgostructtypesassertion

解决方案


我不完全理解你的问题,但你正在做的事情可以很容易地缩短而不影响功能:

    reflectItem := reflect.ValueOf(dataStruct)
    subItem := reflectItem.FieldByName(subItemKey)
    switch subItemVal := subItem.(type) {
        case string:
            searchData = bson.D{{"data." + 
              strings.ToLower(subItemKey), subItemVal}}
        case int64:
            searchData = bson.D{{"data." + 
              strings.ToLower(subItemKey), subItemVal}}
    }

但除此之外,我认为在您的情况下根本不需要类型断言。这也应该有效:

    reflectItem := reflect.ValueOf(dataStruct)
    subItem := reflectItem.FieldByName(subItemKey)
    searchData = bson.D{{"data."+strings.ToLower(subItemKey), subItem.Interface())

推荐阅读