1

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
  • Your struct tags should have backticks, not single quotes. A package like github.com/jmoiron/sqlx can also assist in marshaling rows into structs. Commented Jun 15, 2015 at 22:32

1 Answer 1

2

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()))
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.