Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct's zero value

Tags:

struct

go

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?

like image 765
soapbar Avatar asked Feb 20 '15 09:02

soapbar


People also ask

What is the default value of zero?

If an enum does not define an item with a value of zero, its default value will be zero.

What is the initial value zero value for slice and map?

nil for interfaces, slices, channels, maps, pointers and functions.

Is struct empty Go?

Structure is empty. Explanation: In this example, we created a structure named “articles” in which no fields are declared. Inside the main function, we created a variable “x” and used a switch case to access our structure.


2 Answers

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

like image 133
Denys Séguret Avatar answered Oct 26 '22 09:10

Denys Séguret


I don't believe the top-voted answer is clearly worded to answer the question, so here is a more clear explanation:

"The elements of an array or struct will have its fields zeroed if no value is specified. This initialization is done recursively:"

Source

like image 27
Josh Diehl Avatar answered Oct 26 '22 08:10

Josh Diehl