Using sqlx.Rows.StructScan for interface args

1.9k views Asked by At

I need to use StructScan function for interface (pointer to struct). But if I try to reflect value, I've got error, because reflect.New() returning reflect.Value type. How I can scan structure and store data into dest var?

// package 1
type Data struct {
    id int `db:"id"`
    caption string `db:"caption"`
}

func Func1 {
    data := []Data{}
    GetData(&data)
    log.Println(data)
}

// package 2
func GetData(sql string, dest interface{}) {
    rows, err := DBI.Queryx(sql)
    if err == nil {
        // reflect.Value
        myData := reflect.New(reflect.TypeOf(dest).Elem().Elem())
        for rows.Next() {
            rows.StructScan(&myData) // Fail here

        }
    }
}
1

There are 1 answers

0
Dmitro On BEST ANSWER

Solved

// package 2
func GetData(sql string, dest interface{}) {
    arr := reflect.ValueOf(dest).Elem()
    v := reflect.New(reflect.TypeOf(dest).Elem().Elem())
    rows, err := DBI.Queryx(sql)
    if err == nil {
        if err = rows.StructScan(v.Interface()); err == nil {
            arr.Set(reflect.Append(arr, v.Elem()))
        }
    }
}