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?
If an enum does not define an item with a value of zero, its default value will be zero.
nil for interfaces, slices, channels, maps, pointers and functions.
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.
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
).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With