structgo

Struct's zero value


Here is sample code:

package main

import (
    "fmt"
)

type A struct {
    Name string
}

func (this *A) demo(tag string) {
    fmt.Printf("%#v\n", this)
    fmt.Println(tag)
}

func main() {
    var ele A
    ele.demo("ele are called")

    ele2 := A{}
    ele2.demo("ele2 are called")
}

Run results:

&main.A{Name:""}
ele are called
&main.A{Name:""}
ele2 are called

It looks like those are the same about var ele A and ele2 := A{}

So, the struct's Zero value is not nil, but a struct that all of the property are initialized Zero value. Is the guess right?

If the guess is right, then the nature of var ele A and ele2 := A{} are the same right?


Solution

  • Why guess (correctly) when there's some documentation ?

    When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value.

    Each element of such a variable or value is set to the zero value for its type:

    • false for booleans,
    • 0 for integers,
    • 0.0 for floats,
    • "" for strings,
    • and nil for pointers, functions, interfaces, slices, channels, and maps.

    This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.

    Note that there's no way to set a struct value to nil (but you could set the value of a pointer to a struct to nil).