Search code examples
pointersgostructnew-operatordereference

Golang return struct pointer with New() instead of creating one directly


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
}

Solution

  • 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.