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

huangapple go评论93阅读模式
英文:

How to set struct field using base type in Go

问题

如果我定义了一个类型 type myInt64 int64,我该如何使用反射来设置它?以下是代码,但是会导致 panic:reflect.Set: value of type int64 is not assignable to type main.myInt64。

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)
}
英文:

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

答案1

得分: 7

你必须为赋值提供正确的类型。没有隐式类型转换。

你可以在函数中提供一个 myInt64

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

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

或者你可以在赋值过程中进行值的转换:

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

英文:

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

huangapple
  • 本文由 发表于 2015年11月21日 06:57:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/33837440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定