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

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

類型開關的俱樂部值

類型開關的俱樂部值

Go
米琪卡哇伊 2022-12-05 16:46:12
以下代碼工作正常var requestMap map[string]interface{}for _, value := range requestMap {    switch v := value.(type) {    case []interface{}:        if len(v) == 0 {            // if is empty then no need to throw NA            return http.StatusOK, nil        }    case string:        if len(v) == 0 {            // if is empty then no need to throw NA            return http.StatusOK, nil        }    }}但是下面的代碼給出了invalid argument for len function,我已經閱讀了這個問題var requestMap map[string]interface{}for _, value := range requestMap {    switch v := value.(type) {    case []interface{}, string:        if len(v) == 0 {            // if is empty then no need to throw NA            return http.StatusOK, nil        }    }}這個 case 語句不足以識別[]interface{}或string作為值類型嗎?為什么它仍在考慮interface{}作為參數len()
查看完整描述

2 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

如果在case一個類型開關中列出多個類型,則switch變量的靜態類型將是原始變量的類型。規范:開關語句:

在 case 中僅列出一種類型的子句中,變量具有該類型;否則,該變量具有 TypeSwitchGuard 中表達式的類型。

因此,如果 switch 表達式是v := value.(type)v則匹配案例(列出多種類型)中的 of 將是 的類型value,在您的情況下它將是interface{}。并且內置len()函數不允許傳遞 type 的值interface{}。


查看完整回答
反對 回復 2022-12-05
?
holdtom

TA貢獻1805條經驗 獲得超10個贊

這是因為在類型切換的情況下,v應同時轉換為接口 ( )[]interface和 astring的一部分。編譯器無法決定使用哪個,因此它會將值還原為,因為它可以是任何值。interface{}



查看完整回答
反對 回復 2022-12-05
  • 2 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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