结构体字段是否是必需的?

huangapple go评论76阅读模式
英文:

Are struct fields not mandatory?

问题

我正在学习Go,并遇到了以下代码:

type Something struct {
    someField         string
}

然后它被初始化为:Something{}

我原本以为我们需要用结构体内部的字段来初始化结构体,但是这段代码可以编译和运行,所以有人可以解释一下为什么这样可以吗?

英文:

I am learning Go, and came into something like:

type Something struct {
someField         String
}

That then is initialized as: Something{}

It was my understanding that we needed to initialize struct with the fields inside of it, but this is compiling and working, so can anybody explain me why this works?

答案1

得分: 1

Go语言没有未定义的概念。每种数据类型都有一个"零值"。

任何未显式初始化的变量/字段/属性都会默认初始化为其数据类型的零值。

这是否是一件好事是有争议的[1],但这是Go语言的方式。

[1] 例如,如果我在测量电压,零伏特的测量结果与根本没有测量到电压是不同的。或者如果我在统计调查回答时,没有回应与回应"未知"/"不知道"/"其他"是不同的。

英文:

Go does not have the notion of undefined. Every data type has a zero value.

Any variable/field/property that is not explicitly initialized is initialized by default with the zero value of its data types.

Whether or not that's a good thing is arguable[1], but it is the Go Way™.

[1] For instance, if I'm measuring voltage, a measurement of zero volts is different than not getting a voltage measurement at all. Or if I'm tabulating survey responses, no response is different than a response of "unknown"/"don't know"/"other".

huangapple
  • 本文由 发表于 2022年3月31日 19:21:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/71691596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定