我正在嘗試創建一個查看結構元數據的服務,並確定將哪些字段添加到一起。這是一個示例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