结构的零值

标签 struct go

这里是示例代码:

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 Aele2 := A{}

看起来是一样的

所以,struct 的 Zero 值不是 nil,而是一个 struct 的所有属性都被初始化的 Zero 值。猜对了吗?

如果猜对了,那么var ele Aele2 := 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/

相关文章:

go - sync.Cond 测试广播 - 为什么要循环检查?

vim 去 : How to open files returned by GoFiles

go - 如何构建重复结构

c - 如何在 header 中构造函数,在源代码中定义

c - 创建链表时不需要创建实际节点吗?

c - 我无法为此结构分配内存

go - Scraper 按文本查找元素

mongodb - 由于 x509 证书依赖于旧的 Common Name 字段,因此无法使用 Golang 连接到服务器

mongodb - 如何编写这些golang和mgo代码

c# 将结构转换为另一个结构