Struct Zero in golang

Here is a 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") } 

Execution Results:

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

It looks like the same in var ele A and ele2 := A{}

Thus, the value of struct Zero is not nil , but a structure in which all properties are initialized values โ€‹โ€‹of Zero. Is the assumption correct?

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

+19
struct go
source share
1 answer

Why guess (right) when some documentation is ?

When storage is allocated for a variable, either by declaring, or by calling a new one, or when a new value is created, either through a compound literal or by calling make, and no explicit initialization is provided , the variable or value is assigned the default value.

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

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

This initialization is performed recursively, therefore, for example, each element of the array of structures will have its fields zeroed if no value is specified.

Note that it is not possible to set the value of struct to nil (but you can set the value of a pointer to struct to nil ).

+44
source share

All Articles