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.

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

报告相同问题?

悬赏问题

  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符