英文:
Set reflect.Value to slice in Go
问题
我尝试保存一个整数字段的切片。该字段的类型是reflect.Value。
我遇到了错误:无法将articles(类型为[]int64的变量)作为参数传递给field.Set中的reflect.Value值。我该怎么解决这个问题?
非常感谢!
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 {
// 忽略空值
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)
}
}
}
答案1
得分: 1
mkopriva的答案是:field.Set(reflect.ValueOf(articles))
英文:
The answer of mkopriva: field.Set(reflect.ValueOf(articles))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论