类型断言非简约
Type Assertion Non Parsimonious
我有以下有效的方法:
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())
我有以下有效的方法:
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())