这里是示例代码:
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")
}
运行结果:
&main.A{Name:""}
ele are called
&main.A{Name:""}
ele2 are called
var ele A
和 ele2 := A{}
所以,struct 的 Zero 值不是 nil
,而是一个 struct 的所有属性都被初始化的 Zero 值。猜对了吗?
如果猜对了,那么var ele A
和ele2 := A{}
的性质是一样的吧?
最佳答案
当有 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.
请注意,无法将结构值设置为 nil
(但您可以将指向结构的指针的值设置为 nil
)。
关于结构的零值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28625794/