0

There is a struct User, and what's the differences between user := User{}, var user User and user := new(User) in GoLang?

  • 2
    The first 2 is basically identical, the third will be a pointer to `User`, thus `*User`, same as `user := &User{}`. – icza Jan 25 '21 at 09:58

1 Answers1

3

user := User{} creates a new user struct with default values and is the same as var user User. var user User would be more common to use if no values are set.

user := new(User) creates a variable with a pointer to User (type *User). Identical to user := &User{}. You see the user := &User{} notation more often. The new keyword comes in handy for initializing types like *int or *string to be non-nil.

TehSphinX
  • 6,536
  • 1
  • 24
  • 34