将值动态相加

我正在尝试创建一个查看结构元数据的服务,并将找出要添加在一起的字段。这是一个示例 Struct 和我在 Go Playground 中用来添加东西的函数。这只是一个示例结构,显然并非所有字段都会递增。


“恐慌:接口转换:接口是int,而不是int64”是恐慌,我该如何正确地做到这一点?


package main


import (

   "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


喵喵时光机
浏览 178回答 1
1回答

慕森王

因为这些字段的类型是int,所以您必须输入 assert to&nbsp;int。reflect.ValueOf(&new).Elem().Field(i).SetInt(int64(new_values.Field(i).Interface().(int)&nbsp;+&nbsp;values.Field(i).Interface().(int)))另一种方法是使用Int()而不是 Interface().(int)。这种方法适用于所有有符号整数类型:reflect.ValueOf(&new).Elem().Field(i).SetInt(new_values.Field(i).Int()&nbsp;+&nbsp;values.Field(i).Int())以下是对所有数字类型执行此操作的方法:&nbsp; &nbsp; &nbsp; &nbsp; v := reflect.ValueOf(&new).Elem().Field(i)&nbsp; &nbsp; &nbsp; &nbsp; switch v.Kind() {&nbsp; &nbsp; &nbsp; &nbsp; case reflect.Int,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reflect.Int8,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reflect.Int16,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reflect.Int32,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reflect.Int64:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v.SetInt(new_values.Field(i).Int() + values.Field(i).Int())&nbsp; &nbsp; &nbsp; &nbsp; case reflect.Uint,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reflect.Uint8,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reflect.Uint16,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reflect.Uint32,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reflect.Uint64:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v.SetUint(new_values.Field(i).Uint() + values.Field(i).Uint())&nbsp; &nbsp; &nbsp; &nbsp; case reflect.Float32, reflect.Float64:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v.SetFloat(new_values.Field(i).Float() + values.Field(i).Float())&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go