【问题标题】:Golang return struct pointer with New() instead of creating one directlyGolang 用 New() 返回结构指针,而不是直接创建一个
【发布时间】:2019-09-21 14:22:44
【问题描述】:

我正在阅读这个repo unittest 代码,Client 结构是以我以前从未见过的方式创建的。

type Client struct {
    // client stuff
}

// In client_test.go
// Creating default client for testing
c := dc()

// In resty_test.go
func dc() *Client {
    DefaultClient = New()
    DefaultClient.SetLogger(ioutil.Discard)
    return DefaultClient
}

我的问题是,返回New() 的目的是什么? 下面的代码是否与New() 样式类似?为什么要选择一个而不是另一个?

func dc() *Client {
    DefaultClient := Client{}
    return &DefaultClient
}

【问题讨论】:

  • New() function 函数不是内置的new() 函数。 New() 函数的作用远不止Client{}。我假设测试需要 New() 中的额外初始化。

标签: pointers go struct new-operator dereference


【解决方案1】:

New() 函数是Client 的构造函数:

https://github.com/go-resty/resty/blob/63ac6744519b3b3e976256d87d7b097c3a2c8dbc/default.go#L25

使用构造函数允许使用设置的默认值构造结构,而不是像 Client{} 那样对所有内部字段使用零值。例如,在这种情况下,最大正文大小设置为 math.MaxInt32 而不是 0。

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多