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

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

將reflect.Value從字符串轉換為int

將reflect.Value從字符串轉換為int

Go
蠱毒傳說 2021-11-29 16:23:01
我收到這樣的錯誤reflect.Value.Convert: value of type string cannot be converted to type intgoroutine 6當我運行此代碼時param := "1" // type stringps := fn.In(i) // type intif !reflect.TypeOf(param).ConvertibleTo(ps) {    fmt.Print("Could not convert parameter.\n") // this is printed}convertedParam := reflect.ValueOf(param).Convert(ps)我可以在不創建 switch/case 和多行代碼以轉換為每種類型的情況下以某種方式執行此操作嗎?我只是在尋找最簡單/最好的方法來做到這一點。
查看完整描述

2 回答

?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

類型轉換有特定的規則。字符串不能轉換為數值。

使用該strconv包從字符串中讀取數值。


查看完整回答
反對 回復 2021-11-29
?
白豬掌柜的

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

您可以通過反射值循環使用 switch,這將返回reflect.Value kind() 以返回該值的確切類型


v := reflect.ValueOf(s interface{})

for t := 0; i < v.NumField(); i++ {

fmt.Println(v.Field(i)) // it will prints the value at index in interface

switch t := v.Kind() {

    case bool:

        fmt.Printf("boolean %t\n", t) // t has type bool

    case int:

        fmt.Printf("integer %d\n", t) // t has type int

    case *bool:

        fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool

    case *int:

        fmt.Printf("pointer to integer %d\n", *t) // t has type *int

    default:

        fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has

    }

}

要將接口中的類型轉換為另一種類型,首先在變量中獲取它的值,然后使用類型轉換來轉換該值


查看完整回答
反對 回復 2021-11-29
  • 2 回答
  • 0 關注
  • 535 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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