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中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器