Object 类型断言不节省

Object 类型断言不节省,object,go,struct,types,assertion,Object,Go,Struct,Types,Assertion,我有以下几种方法,它们是有效的: reflectItem := reflect.ValueOf(dataStruct) subItem := reflectItem.FieldByName(subItemKey) switch subItem.Interface().(type) { case string: subItemVal := subItem.Interface().(string)

我有以下几种方法,它们是有效的:

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

问题是,这似乎非常不节俭。我非常希望只获取子项的类型,而不使用switch语句,该语句在按名称查找字段后简单地断言回它自己的类型。然而,我不知道该如何反驳这一点。想法?

我不完全理解您的问题,但您所做的可以很容易地缩短,而不会影响功能:

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

你是说像?不-我根本不想要switch语句-它似乎没有必要。对不起,我不明白。这就是类型切换的要点,它是有条件地断言多个可能的类型。你可以去掉开关,也可以去掉单独的断言,但不能两者都去掉。嗯……我想立刻抓住字段和类型。我不能那样做似乎很疯狂。为什么我不能那样做?对不起,我还是不明白。子项是一个反射值,您可以将该类型作为reflect.type检查,但它不是实类型,只能在反射中使用。然而,这里的示例甚至不需要类型断言,因为不管类型如何,您都在做同样的事情,您可以将subItem.Interface放在bson.D中。我还不完全习惯严格类型的语言。谢谢你的回复。