go - 是否需要为变量分配默认值?

标签 go default default-value

在 Go 中,当一个变量被声明时,它会按照规范中的描述用零值初始化。

http://golang.org/ref/spec#The_zero_value

但是,如果需要使用默认值初始化变量,则使用此属性并且不要显式初始化变量是否是一种良好的编码习惯。

例如在下面的例子中

http://play.golang.org/p/Mvh_zwFkOu

package main

import "fmt"

type B struct {
    isInit bool
    Greeting string
}

func (b *B) Init() {
    b.isInit = true
    b.Greeting = "Thak you for your time"
}

func (b *B) IsInitialized() bool {
    return b.isInit
}

func main() {
    var b B
    if !b.IsInitialized(){
        b.Init()
    }
    fmt.Println(b.Greeting)
}

程序依赖 boolean 的默认值为 false。

最佳答案

正如大家所说,这里的规范很明确:所有内存都被初始化(归零)。您应该像标准软件包一样利用这一点。特别是,它允许您为自己的类型依赖“默认构造函数”,并且经常跳过 New() *T 类型的函数以支持 &T{}

标准包中的许多类型都利用了这一点,一些示例:

http.Client

A Client is an HTTP client. Its zero value (DefaultClient) is a usable client that uses DefaultTransport.

然后你会发现var DefaultClient = &Client{} 声明在包中。

http.Server

A Server defines parameters for running an HTTP server. The zero value for Server is a valid configuration.

bytes.Buffer

A Buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is an empty buffer ready to use.

这很棒,因为您可以执行 var buf bytes.Buffer 并开始使用它。因此,您还会经常看到 bool 成员变量以“否定”形式使用——例如 tls.Config 中的 InsecureSkipVerify不称为 Verify,因为默认行为不会验证证书(我想 false - 或零 - 值用于理想的默认值)。

最后,回答你的问题:

But is it good coding practice to make use of this property and do not explicitly initialize your variable if it needs to be initialized with default value?

是的。

关于go - 是否需要为变量分配默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31581867/

相关文章:

default - 更改Pycharm项目的默认位置

javascript - 为什么visible(render)属性的默认值会覆盖我在Xpages中设置的值

postgresql - 当仅提供 timestamptz 中的日期时强制执行默认时间

Freemarker - 变量的默认值可能丢失或为空?

go - 无法获得环境值(value)

c++ - Go 可以在页面级别使用内存吗?

default - 默认情况下为 H2 数据库引擎中 UUID 类型的列上的每一行生成 UUID 值

scala - Scala 中带有选项值或默认参数的方法调用

go - : variable <-struct {}{}的含义

go - 已评估但未使用