英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论