Search code examples
gosyntaxexpressionrules

What does a pair of round brackets syntax expression mean in Go?


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?


Solution

  • 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)