Decode sql.Rows into structs without having to remember ordinal positions. sqldecoder supports maps structs fields to SQL columns without reflection using an interface, ColumnMapper. Alternatively, sqldecoder will use reflection to map tagged struct fields or struct field names to SQL columns. If the struct neither implements ColumnMapper nor has tags, sqldecoder expects the column names and field names to match exactly.
Regardless of whether a struct implements the ColumnMapper interface or not, using sqldecoder is the same:
func GetPeople(r *sql.Rows) (people []Person){
personDecoder, err := decoder.NewDecoder(rows)
if err != nil {
return nil
}
people := make([]Person, 4)
for {
someone := Person{}
if err := decoder.Decode(&someone); err == io.EOF {
break
} else {
append(people, someone)
}
}
return people
}Implement ColumnMapper
type Person struct {
firstName string
lastName string
}
func (p *Person) ColumnMap() ColumnMap{
return ColumnMap{ "FirstName": &p.firstName, "LastName": &p.lastName }
}type Person struct{
First_Name string `db:"FirstName"`
Last_Name string `db:"LastName"`
}type Person struct{
FirstName string
LastName string
}