我正在尝试创建一个查看结构元数据的服务,并确定将哪些字段添加到一起。这是一个示例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
为什么不https://开头的发挥。 golang.org/p/tdPvvVLjo7? –
有没有办法让它更具动感?像任何类型的int/float? – electrometro