如何在Go中使用基本类型设置结构字段

If I defined a type type myInt64 int64 how would I set it using reflection? Code below panics reflect.Set: value of type int64 is not assignable to type main.myInt64 http://play.golang.org/p/scsXq4ofk6

package main

import (
    "fmt"
    "reflect"
)

type myInt64 int64

type MyStruct struct {
    Name string
    Age  myInt64
}

func FillStruct(m map[string]interface{}, s interface{}) error {
    structValue := reflect.ValueOf(s).Elem()

    for name, value := range m {
        structFieldValue := structValue.FieldByName(name)

        val := reflect.ValueOf(value)

        structFieldValue.Set(val)
    }
    return nil
}

func main() {
    myData := make(map[string]interface{})
    myData["Name"] = "Tony"
    myData["Age"] = int64(23)

    result := &MyStruct{}
    err := FillStruct(myData, result)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(result)
}

You have to provide the correct type for the assignment. There are no implicit type conversions.

You can either provide a myInt64 to your function

myData := make(map[string]interface{})
myData["Name"] = "Tony"
myData["Age"] = myInt64(23)

http://play.golang.org/p/sbOdAnbz8n

Or you can convert the values during assignment

for name, value := range m {
    structFieldValue := structValue.FieldByName(name)
    fieldType := structFieldValue.Type()

    val := reflect.ValueOf(value)

    structFieldValue.Set(val.Convert(fieldType))
}

http://play.golang.org/p/kl0fEENY9b