Is it required to assign default value to variable?

As everyone says, specification is clear here: all memory is initialised (zeroed). You should take advantage of this as standard packages do. In particular, it allows you to rely on "default constructor" for your own types and often skip New() *T kind of functions in favour of &T{}.

Many types in standard packages take advantage of this, some examples:

http.Client

A Client is an HTTP client. Its zero value (DefaultClient) is a usable client that uses DefaultTransport.

And then you will find var DefaultClient = &Client{} declared in the package.

http.Server

A Server defines parameters for running an HTTP server. The zero value for Server is a valid configuration.

bytes.Buffer

A Buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is an empty buffer ready to use.

This is great, because you can just do var buf bytes.Buffer and start using it. As a consequence of this you will also often see boolean member variables to be used in a "negated" form – for example InsecureSkipVerify in tls.Config is not called Verify, because the default behaviour wouldn't then validate certificates (think I want the false – or zero – value to be used for desirable defaults).

Finally, answering your question:

But is it good coding practice to make use of this property and do not explicitly initialize your variable if it needs to be initialized with default value?

Yes, it is.


Initialize variables to their zero values only if you want to use the short declaration syntax.

//less verbose than ''var count int''
count := 0
empty := ""

Otherwise, initializing them explicitly is just noise. You might think that there's something wrong with uninitialized variables... and you'd be right. Fortunately, there's no such thing in go. Zero values are part of the spec and they're not going to suddenly change.


When a variable is declared it contains automatically the default zero or null value for its type: 0 for int, 0.0 for float, false for bool, empty string for string, nil for pointer, zero-ed struct, etc.

All memory in Go is initialized!.

For example: var arr [5]int in memory can be visualized as:

+---+---+---+---+ | | | | | +---+---+---+---+ 0 1 2 3

When declaring an array, each item in it is automatically initialized with the default zero-value of the type, here all items default to 0.

So preferably it's better to initialize without default value, in other cases than the situations when you explicitly want to declare a variable with a default value.