object - 类型断言非简约
问题描述
我有以下,它的工作原理:
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())
推荐阅读
- javascript - 调试javascript函数
- excel - 在 Excel 中创建具有序号的唯一 ID
- python - 跳过循环的一次迭代
- sql - 布尔值 - 表中是否存在 ID?
- c# - 将查询表达式转换为 Linq C#
- react-native - React Native 中的 64 位应用程序
- string - 从 sd 卡中的 .txt 文件到 Arduino 中的字符串变量
- html - 如何在 HTML 中精确获取 svg 路径的边界?
- c - 为什么 read() 返回不正确的字节数?
- spring-data-elasticsearch - spring-data-elasticsearch:结果窗口太大(index.max_result_window)