rocco
rocco

Reputation: 47

Dynamically generate struct fields from SQL QueryRow result

I want to retrieve all fields of the row and than render them to html. I know how to do it and here is a code for a row with 3 fields:

type View struct {
    Id         int
    Name_and_requisits string
    Reg_Date  string
}
func getViewById(id int) (*View, error){
    var vie View
    row := db.QueryRow("select id, name_and_requisits, reg_date from book where id = ?;", id)
    err := row.Scan(&vie.Id, &vie.Name_and_requisites, &vie.Reg_Date)
    if err != nil {
        return nil, err
    }

    return &vie, nil
}

But in my table one row includes about 20 columns and i need all of them with their names but i dont want to create a nasted hardcoded struct. I have an idea like to generate struct fields dynamically, from names of columns, and than use row.Scan on it. Any ideas? Maybe map is better for this situation?

Thanks!

Upvotes: 0

Views: 542

Answers (1)

Volker
Volker

Reputation: 42413

generate struct fields dynamically

https://golang.org/pkg/reflect/#StructOf

But please: Don't do it.

Upvotes: 3

Related Questions