设置Reflect.Value在Go中切片
我试图保存一个字段的整数。该字段是类型反射。值。
我得到错误:不能将文章(类型[] Int64的变量)作为反射。在field.set中的参数中值。我该怎么办?
非常感谢!
for i := 0; i < elem.Type().NumField(); i++ {
structField := elem.Type().Field(i)
tag := structField.Tag.Get("db")
fieldType := structField.Type
fieldName := structField.Name
val, ok := record.Get(fmt.Sprintf("%s", tag))
if ok {
// Ignore nil values
if val == nil {
continue
}
field := elem.FieldByName(fieldName)
if field.IsValid() {
t := fieldType.String()
switch t {
case "string":
field.SetString(val.(string))
case "int64":
field.SetInt(val.(int64))
case "float64":
field.SetFloat(val.(float64))
case "boolean":
field.SetBool(val.(bool))
case "[]int64":
articles := []int64{}
initData := []interface{}{
val,
}
for _, data := range initData {
for _, v := range data.([]interface{}) {
t := v
articles = append(articles, t.(int64))
}
}
//
field.Set(articles)
default:
return fmt.Errorf("Invalid type: %s", t)
}
}
}
I try to save a slice of integers of a field. the field is type reflect.Value.
I get the error: cannot use articles (variable of type []int64) as reflect.Value value in argument to field.Set. What can I do to encounter that?
Thank you very much!
for i := 0; i < elem.Type().NumField(); i++ {
structField := elem.Type().Field(i)
tag := structField.Tag.Get("db")
fieldType := structField.Type
fieldName := structField.Name
val, ok := record.Get(fmt.Sprintf("%s", tag))
if ok {
// Ignore nil values
if val == nil {
continue
}
field := elem.FieldByName(fieldName)
if field.IsValid() {
t := fieldType.String()
switch t {
case "string":
field.SetString(val.(string))
case "int64":
field.SetInt(val.(int64))
case "float64":
field.SetFloat(val.(float64))
case "boolean":
field.SetBool(val.(bool))
case "[]int64":
articles := []int64{}
initData := []interface{}{
val,
}
for _, data := range initData {
for _, v := range data.([]interface{}) {
t := v
articles = append(articles, t.(int64))
}
}
//
field.Set(articles)
default:
return fmt.Errorf("Invalid type: %s", t)
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Mkopriva的答案:field.set(反射valueof(文章))
The answer of mkopriva: field.Set(reflect.ValueOf(articles))