douben8492 2019-05-03 03:42
浏览 234
已采纳

Golang使用New()返回结构指针,而不是直接创建一个

I'm reading this repo unittest code and the Client struct is created in a way that I never seen before.

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
}

My question is that what is the purpose of returning New()? Does the code below behave similarly as the New() style? Why should choose one over another?

func dc() *Client {
    DefaultClient := Client{}
    return &DefaultClient
}
  • 写回答

1条回答 默认 最新

  • dpnw86361 2019-05-03 04:16
    关注

    The New() function is a constructor function for the Client:

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

    Using a constructor function allows for structs to be constructed with default values set instead of using the zero values for all the internal fields like doing Client{} would do. For instance, the maximum body size is set to math.MaxInt32 not 0 in this case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?