类型断言非简约[重复]

This question already has an answer here:

I have the following, which works:

        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}}
        }

The issue is that this seems very non-parsimonious. I would very much like to simply get the type of subItem without having a switch statement that simply asserts back its own type after finding the field by name. I'm not sure how to back this out however. Ideas?

</div>

I don't understand your question exactly, but what you're doing can be easily shortened without affecting functionality:

    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}}
    }

But beyond that, I don't think a type assertion is necessary in your case at all. This should also work:

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