I have the following struct
which contains a net/http.Request
:
type MyRequest struct {
http.Request
PathParams map[string]string
}
Now I want to initialize the anonymous inner struct http.Request
in the following function:
func New(origRequest *http.Request, pathParams map[string]string) *MyRequest {
req := new(MyRequest)
req.PathParams = pathParams
return req
}
How can I initialize the inner struct with the parameter origRequest
?
req := new(MyRequest)
req.PathParams = pathParams
req.Request = origRequest
or...
req := &MyRequest{
PathParams: pathParams
Request: origRequest
}
See: http://golang.org/ref/spec#Struct_types for more about embedding and how the fields get named.
What about:
func New(origRequest *http.Request, pathParams map[string]string) *MyRequest {
return &MyRequest{*origRequest, pathParams}
}
It shows that instead of
New(foo, bar)
you might prefer just
&MyRequest{*foo, bar}
directly.
As Jeremy shows above, the "name" of an anonymous field is the same as the type of the field. So if the value of x were a struct containing an anonymous int, then x.int would refer to that field.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.