第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

將值動態(tài)相加

將值動態(tài)相加

Go
喵喵時光機(jī) 2021-12-07 18:40:05
我正在嘗試創(chuàng)建一個查看結(jié)構(gòu)元數(shù)據(jù)的服務(wù),并將找出要添加在一起的字段。這是一個示例 Struct 和我在 Go Playground 中用來添加?xùn)|西的函數(shù)。這只是一個示例結(jié)構(gòu),顯然并非所有字段都會遞增?!翱只牛航涌谵D(zhuǎn)換:接口是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貢獻(xiàn)1777條經(jīng)驗 獲得超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)。這種方法適用于所有有符號整數(shù)類型:

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

以下是對所有數(shù)字類型執(zhí)行此操作的方法:


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

        }


查看完整回答
反對 回復(fù) 2021-12-07
  • 1 回答
  • 0 關(guān)注
  • 206 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號