0

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?

Fred Hors
  • 3,258
  • 3
  • 25
  • 71

2 Answers2

7

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)
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • So this is needed in this case only? To convert a nil to *Type interface? – Fred Hors Feb 27 '20 at 23:39
  • If you're talking about typecasting, you'd need it if the value is not nil as well, like (*SomePtr)(someValue). You can use this, for instance, to copy a struct value to another with a different but compatible type. – Burak Serdar Feb 28 '20 at 01:56
  • Isn't converting value to type Book like this: (Book)v – Stan Nov 09 '22 at 05:26
2

'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