在使用 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学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
