0

I would like to make this function more generic (with a "for")

func (e example) ScanRow(rows *sql.Rows) (example, error) {
    val := reflect.ValueOf(e)
    test := make([]interface{}, val.Type().NumField())

    test[0] = &e.Id
    test[1] = &e.CreatedAt
    test[2] = &e.Text
    test[3] = &e.AuthorId
    test[4] = &e.CategoryId

    if err := rows.Scan(test[0], test[1], test[2], test[3], test[4]); err != nil {
        return e, err
    }
    return e, nil
}

Here is the struct example:

type example struct {
    Id      int `json:"id"`
    CreatedAt   string `json:"created_at"`
    Text        string `json:"text"`
    AuthorId    int `json:"author_id"`
    CategoryId  int `json:"category_id"`
}

Do you think it's possible ? I am trying to find a way to do that but i am lost...

Rick-777
  • 9,714
  • 5
  • 34
  • 50
lambher
  • 433
  • 1
  • 4
  • 6
  • Why not just use [`sqlx`](https://github.com/jmoiron/sqlx)? – Ainar-G Nov 29 '16 at 15:53
  • You can get fields via reflection using https://golang.org/pkg/reflect/#Value.Field. But ya, `sqlx` would do it all for you. Its `Get()` (and `Select()`) method let you just hand an arbitrary structure (or slice of structures) to the query and it'll fill the struct fields by tag or name automagically. – Kaedys Nov 29 '16 at 16:25
  • this might help you - http://stackoverflow.com/a/18927729/3563197 – vedhavyas Nov 29 '16 at 16:55
  • Okey sqlx is perfect, it's the kind of library I was looking for ! – lambher Nov 29 '16 at 16:57

0 Answers0