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

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

將值動態相加

將值動態相加

Go
喵喵時光機 2021-12-07 18:40:05
我正在嘗試創建一個查看結構元數據的服務,并將找出要添加在一起的字段。這是一個示例 Struct 和我在 Go Playground 中用來添加東西的函數。這只是一個示例結構,顯然并非所有字段都會遞增?!翱只牛航涌谵D換:接口是int,而不是int64”是恐慌,我該如何正確地做到這一點?package mainimport (   "fmt"   "reflect"   "strconv")type TestResult struct {    Complete         int        `json:"complete" increment:"true"`    Duration         int        `json:"duration" increment:"true"`    Failed           int        `json:"failed" increment:"true"`    Mistakes         int        `json:"mistakes" increment:"true"`    Points           int        `json:"points" increment:"true"`    Questions        int        `json:"questions" increment:"true"`    Removal_duration int        `json:"removal_duration" increment:"true"`}func main() {    old := TestResult{}    new := TestResult{}    old.Complete = 5    new.Complete = 10    values := reflect.ValueOf(old)    new_values := reflect.ValueOf(new)    value_type := reflect.TypeOf(old)    fmt.Println(values)    fmt.Println(new_values)    for i := 0; i < values.NumField(); i++ {       field := value_type.Field(i)       if increment, err := strconv.ParseBool(field.Tag.Get("increment")); err == nil && increment {          reflect.ValueOf(&new).Elem().Field(i).SetInt(new_values.Field(i).Interface().(int64) + values.Field(i).Interface().(int64))       }    }    fmt.Println(new)}游樂場:https : //play.golang.org/p/QghY01QY13
查看完整描述

1 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

因為這些字段的類型是int,所以您必須輸入 assert to int。

reflect.ValueOf(&new).Elem().Field(i).SetInt(int64(new_values.Field(i).Interface().(int) + values.Field(i).Interface().(int)))

另一種方法是使用Int()而不是 Interface().(int)。這種方法適用于所有有符號整數類型:

reflect.ValueOf(&new).Elem().Field(i).SetInt(new_values.Field(i).Int() + values.Field(i).Int())

以下是對所有數字類型執行此操作的方法:


        v := reflect.ValueOf(&new).Elem().Field(i)

        switch v.Kind() {

        case reflect.Int,

            reflect.Int8,

            reflect.Int16,

            reflect.Int32,

            reflect.Int64:

            v.SetInt(new_values.Field(i).Int() + values.Field(i).Int())

        case reflect.Uint,

            reflect.Uint8,

            reflect.Uint16,

            reflect.Uint32,

            reflect.Uint64:

            v.SetUint(new_values.Field(i).Uint() + values.Field(i).Uint())

        case reflect.Float32, reflect.Float64:

            v.SetFloat(new_values.Field(i).Float() + values.Field(i).Float())

        }


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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