duanbu9345 2015-07-23 08:21
浏览 223
已采纳

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

In Golang when a variable is declared it is initialized with zero value as described in the specification.

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

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

for example in the following example

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

the program relies on the default value of boolean to be false.

  • 写回答

3条回答 默认 最新

  • dongzhashou0116 2015-07-23 13:19
    关注

    As everyone says, specification is clear here: all memory is initialised (zeroed). You should take advantage of this as standard packages do. In particular, it allows you to rely on "default constructor" for your own types and often skip New() *T kind of functions in favour of &T{}.

    Many types in standard packages take advantage of this, some examples:

    http.Client

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

    And then you will find var DefaultClient = &Client{} declared in the package.

    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.

    This is great, because you can just do var buf bytes.Buffer and start using it. As a consequence of this you will also often see boolean member variables to be used in a "negated" form – for example InsecureSkipVerify in tls.Config is not called Verify, because the default behaviour wouldn't then validate certificates (think I want the false – or zero – value to be used for desirable defaults).

    Finally, answering your question:

    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?

    Yes, it is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python安卓开发
  • ¥15 使用R语言GD包一直不出结果
  • ¥15 计算机微处理器与接口技术相关问题,求解答图片的这个问题,有多少个端口,端口地址和解答问题的方法和思路,不要AI作答
  • ¥15 如何根据一个截图编写对应的HTML代码
  • ¥15 stm32标准库的PID角度环
  • ¥15 ADS已经下载好了,但是DAS下载不了,一直显示这两种情况,有什么办法吗,非常急!
  • ¥100 Excel 点击发送自动跳转outlook邮件
  • ¥15 gis中用栅格计算器或加权总和后图层不显示,值也明显不对
  • ¥15 python使用python-pptx如何给幻灯片添加只读密码。
  • ¥15 oracle数据库备份表如何操作