Reading this https://github.com/go-pg/pg/wiki/Writing-Queries#select I see many times this expression:
(*Book)(nil)
Example:
count, err := db.Model((*Book)(nil)).Count()
What does it mean?
Reading this https://github.com/go-pg/pg/wiki/Writing-Queries#select I see many times this expression:
(*Book)(nil)
Example:
count, err := db.Model((*Book)(nil)).Count()
What does it mean?
That is a type conversion. Assuming the db.Model
function takes interface{}
, it sends an nil interface of type *Book
to the function.
To convert a value v
to type Book
, you'd write:
Book(v)
However, you cannot write Book(nil)
because nil
is a pointer and Book
is not. If you had a type
type BookPtr *Book
Then you could've written BookPtr(nil)
. Extending that, you want to write *Book(nil)
, but that means *(Book(nil))
which is invalid, hence:
(*Book)(nil)
'nil' is to Go what NULL/null is to other languages like C#/Java, etc. The *Variable is just getting the pointer value for the Book object of Model.
So in this case, I believe what's happening here is that (*Book)(nil) is setting the pointer value of the Book object of the Model to nil(/null).
Hope this helps in some way.
Good Resource: https://go101.org/article/nil.html