简体   繁体   中英

Set reflect.Value to slice in Go

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

            }
        }

在此处输入图像描述

mkopriva 的答案:field.Set(reflect.ValueOf(articles))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM