I was following this tutorial on PostgreSQL in Go and it has the following line:
bks := make([]*Book, 0)
Which is part of the bigger code block:
bks := make([]*Book, 0)
for rows.Next() {
bk := new(Book)
err := rows.Scan(&bk.isbn, &bk.title, &bk.author, &bk.price)
if err != nil {
log.Fatal(err)
}
bks = append(bks, bk)
}
Why does the author pass 0 in make
? I understand that's the length, but why 0 length? And why is it an array of pointers instead of an array of books? Wouldn't you want a slice so you can insert books arbitrarily into it?
Wouldn't you want a slice so you can insert books arbitrarily into it?
make([]Type, initLength)
creates a slice of values of type Type
. When initLength > 0
then the slice is pre-filled with that many number of zero-value instances of type Type
. In this case the author doesn't want to have any zero-values, and instead chooses to append non-zero values as they're received from the DB. So bks
is indeed a slice.
Example: http://play.golang.org/p/g0dALT-sLn
More information: http://blog.golang.org/go-slices-usage-and-internals
And why is it a slice of pointers instead of an slice of books?
This is hard to answer without more context. Using a pointer to Book will allow you to store nil
values, which might be useful depending on how bks
is used.
The tutorial you linked to doesn't show bks
being used in any way that makes use of the fact the values are pointers. You could probably convert the slice to type []Book
without any problems.