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

Is it required to assign default value to variable?

在 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)
}

程序依赖布尔值的默认值为假。

仅当您想使用短声明语法时才将变量初始化为零值。

//less verbose than ''var count int''
count := 0
empty := ""

否则,显式初始化它们只是噪音。 您可能认为未初始化的变量有问题……您是对的。幸运的是,go 中没有这样的东西。零值是 规范的一部分,它们不会突然改变。

声明变量时,它会自动包含其类型的默认 zeronull 值:0 代表 int0.0 代表 floatfalse 用于 bool、空字符串用于 stringnil 用于指针、零化结构等

Go中的所有内存都已初始化!.

例如:var arr [5]int在内存中可以形象化为:

+---+---+---+---+ | | | | | +---+---+---+---+ 0 1 2 3

声明数组时,其中的每一项都会自动初始化为该类型的默认零值,这里所有项都默认为 0。

因此,最好在没有默认值的情况下进行初始化,在其他情况下,而不是在您明确想要声明具有默认值的变量的情况下。

正如大家所说,这里的规范很明确:所有内存都已初始化(归零)。您应该像标准包一样利用它。特别是,它允许您依赖 "default constructor" 作为您自己的类型,并且经常跳过 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 即可开始使用它。因此,您还会经常看到以 "negated" 形式使用的布尔成员变量——例如 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?

是的,是的。