2016-02-04 63 views
1

我正在尝试创建一个查看结构元数据的服务,并确定将哪些字段添加到一起。这是一个示例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

+0

为什么不https://开头的发挥。 golang.org/p/tdPvvVLjo7? –

+0

有没有办法让它更具动感?像任何类型的int/float? – electrometro

回答

3

因为字段int类型的,你必须键入断言到int

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

playground example

另一种方法是使用Int()代替接口()。(INT)。这种方法适用于所有符号整型:

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

playground example

这里是如何做到这一点的所有数值类型:

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

playground example

+0

谢谢,这正是我正在寻找的。 – electrometro