postgresql - Creating an array/slice to store DB Query results in Golang -


i'm getting started golang , i'm attempting read several rows postgres users table , store result array of user structs model row.

type user struct {     id  int     title string }  func find_users(db *sql.db) {     // query db     rows, err := db.query(`select u.id, u.title users u;`)     if err != nil { log.fatal(err) }      // initialize array slice of users. size use here?      // don't know number of results beforehand     var users = make([]user, ????)      // loop through each result record, creating user struct each row     defer rows.close()     := 0; rows.next(); i++ {         err := rows.scan(&id, &title)         if err != nil { log.fatal(err) }          log.println(id, title)         users[i] = user{id: id, title: title}     }      // .... stuff } 

as can see, problem want initialize array or slice beforehand store db records, don't know ahead of time how many records there going be.

i weighing few different approaches, , wanted find out of following used in golang community -

  1. create large array beforehand (e.g. 10,000 elements). seems wasteful

  2. count rows explicitly beforehand. work, need run 2 queries - 1 count , 1 results. if query complex (not shown here), that's duplicating logic in 2 places. alternatively can run same query twice, first loop through , count rows. work, seems unclean.

  3. i've seen examples of expanding slices. don't quite understand slices enough see how adapted here. if i'm expanding slice 10k times, seems wasteful.

thanks!

go has built-in append function purpose. takes slice , 1 or more elements , appends elements slice, returning new slice. additionally, 0 value of slice (nil) slice of length zero, if append nil slice, work. thus, can do:

type user struct {     id    int     title string }  func find_users(db *sql.db) {     // query db     rows, err := db.query(`select u.id, u.title users u;`)     if err != nil {         log.fatal(err)     }     defer rows.close()      var users []user     rows.next() {         err := rows.scan(&id, &title)         if err != nil {             log.fatal(err)         }          log.println(id, title)         users = append(users, user{id: id, title: title})     }     if err := rows.err(); err != nil {         log.fatal(err)     }      // ... } 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -