implicit initialization in golang declarations?

123 views
Skip to first unread message

Alexander Mills

unread,
Feb 11, 2020, 12:57:48 AM2/11/20
to golang-nuts
I have been confused about this ever since I started working with Go:



we can do this:

var wg sync.WaitGroup

instead of having to write this:

var wg sync.WaitGroup = sync.WaitGroup{}  // is this initialization implicit, and why?


anyone know why, or what it's called? Is this intialization implicit / automatic and what is the reasoning for this?

-alex

Kurtis Rader

unread,
Feb 11, 2020, 1:13:09 AM2/11/20
to Alexander Mills, golang-nuts
On Mon, Feb 10, 2020 at 9:58 PM Alexander Mills <alexande...@gmail.com> wrote:
we can do this:

var wg sync.WaitGroup

instead of having to write this:

var wg sync.WaitGroup = sync.WaitGroup{}  // is this initialization implicit, and why?


anyone know why, or what it's called? Is this intialization implicit / automatic and what is the reasoning for this?

The two are equivalent due to implicit initialization of vars to their "zero" value. See https://yourbasic.org/golang/default-zero-value/ for one of many explanations of this topic. I'll leave it to others to opine whether the implicit initialization is good style or whether the explicit initialization in your second example is preferable. Having said that, I don't see any reason to prefer the explicit initialization since it is 100% equivalent to the implicit initialization and thus redundant.

--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank
Reply all
Reply to author
Forward
0 new messages