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 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置