2016-02-04 30 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