Home > Software design >  When `User` is struct, what is `(*User)(nil)`?
When `User` is struct, what is `(*User)(nil)`?

Time:10-08

This compiles:

package main

import (
    "fmt"
)

type User struct {
    ID int64
}

func main() {
    v := (*User)(nil)
    fmt.Println(v)
}

Here, what is (*User)(nil)? I encountered this notation at go-pg, and had no clue to find an answer because it was very hard to search on google.

CodePudding user response:

If User is a type, *User is another type, a pointer type, a pointer to User.

(*User)(nil) is a type conversion: it converts the untyped nil predeclared identifier to (*user). You must put *User into parenthesis, else the expression would try to convert nil to User (which is a compile-time error if User is a struct), and then dereference it.

So v will be a variable of type *User, holding the nil pointer value.

The v := (*User)(nil) expression is a short variable declaration and it is equivalent (shorthand) to the following variable declaration:

var v *User = nil

Which is of course the same as

var v *User

Because if the initialization expression is missing, the variable will be initialized to its zero value which is nil for all pointer types.

  • Related