0

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!

2

1 Answer 1

3

generate struct fields dynamically

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

But please: Don't do it.

Sign up to request clarification or add additional context in comments.

3 Comments

"Don't do it". Hah, no kidding. People always come from Python and want crazy weird flexibility without realizing that Go is a statically typed language, and that it's a good thing.
your guidance is worthy of a +1
@RayfenWindspear you right, Python is my background:) And less flexibility is a good thing in Go, i agree. It's like crazy flexibility of Joomla with crazy hangs vs self-maded CMS

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.