I've this snippet of code that works:
db, err := sql.Open("mysql", "pwd@tcp(ip:port)/db")
if err != nil {
panic(err.Error())
}
rows, err := db.Query("select username from users")
if err != nil {
panic(err.Error())
}
var (
username string
)
for rows.Next() {
err = rows.Scan(
&name,
)
if err != nil {
panic(err)
}
fmt.Println(username)
}
But, ... is it possible to substitute
var (
username string
)
and err = rows.Scan( &name, )
with a struct?
I ask this because every time I want to add new field I need to
- add field inside the query
- create new variable in "var" block
- add variable to scan
May I define a struct and update fields in just one place? Or, ... are there some best practice to build queries and fetch them?
&usernamein therows.Scan()?