登录
首页 >  Golang >  Go问答

类型断言不简单

来源:stackoverflow

时间:2024-03-25 21:27:34 194浏览 收藏

在使用 Go 反射获取结构体字段的值时,通过类型断言来获取字段类型显得过于繁琐。本文提供了两种优化方法: * 使用更简洁的语法进行类型断言,从而减少 switch 语句的使用。 * 完全避免类型断言,直接获取字段的接口值。

问题内容

我有以下有效的方法:

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 语句,该语句在按名称查找字段后简单地断言其自己的类型。但我不知道如何支持这一点。有想法吗?


解决方案


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

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

今天关于《类型断言不简单》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>