I want to use Scan() in package sql, but the number of columns, and hence the number of arguments, will change at runtime. This is the signature of Scan():
func (rs *Rows) Scan(dest ...interface{}) error According to the documentation, *interface{} is one of the types accepted by Scan(). So I want to create a slice of []*interface{} and that expand as arguments.
This is what I thought would work:
func query(database *sql.DB) { rows, _ := database.Query("select * from testTable") for rows.Next() { data := make([]*interface{}, 2) err := rows.Scan(data...) // Compilation error fmt.Printf("%v%v\n", *data[0], *data[1]) if err != nil { fmt.Println(err.Error()) } } } Compilation fails with cannot use data (type []*interface {}) as type []interface {} in argument to rows.Scan. I thought that data... would expand to &data[0], &data[1], but apparently not. I don't understand the error message. *interface{} is compatible with interface{}, so why can't I expand the slice of pointers to interface types?
This works:
func query(database *sql.DB) { rows, _ := database.Query("select * from testTable") for rows.Next() { data := make([]*interface{}, 2) err := rows.Scan(&data[0], &data[1]) // Only changed this line fmt.Printf("%v%v\n", *data[0], *data[1]) // Outputs "[48][116 101 120 116]" if err != nil { fmt.Println(err.Error()) } } } I can't use this however, because the number of columns is unknown at compile time. How can I write this code so that I can pass a variable number of *interface{} to rows.Scan()?
[]*interface{}instead of[]interface{}?[]*interface{}gets me closest to the answer. I will edit my question to add this detail.