亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

非簡約類型斷言

非簡約類型斷言

Go
料青山看我應如是 2023-06-12 16:36:35
我有以下內容,有效:        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 語句。但是,我不確定如何支持它。想法?
查看完整描述

1 回答

?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

我不完全理解你的問題,但你正在做的事情可以很容易地縮短而不影響功能:


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


查看完整回答
反對 回復 2023-06-12
  • 1 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號