Search code examples
godefaultdefault-value

Is it required to assign default value to variable?


In Go, when a variable is declared it is initialized with zero value as described in the specification.

http://golang.org/ref/spec#The_zero_value

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

for example in the following example

http://play.golang.org/p/Mvh_zwFkOu

package main

import "fmt"

type B struct {
    isInit bool
    Greeting string
}

func (b *B) Init() {
    b.isInit = true
    b.Greeting = "Thak you for your time"
}

func (b *B) IsInitialized() bool {
    return b.isInit
}

func main() {
    var b B
    if !b.IsInitialized(){
        b.Init()
    }
    fmt.Println(b.Greeting)
}

The program relies on the default value of boolean to be false.


Solution

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