Initializing an Embedded Struct in Go
When working with embedded structs in Go, a common scenario involves initializing the inner anonymous struct. This article addresses such a scenario, providing a clear understanding of how to achieve initialization using two approaches.
Consider the following embedded struct MyRequest:
type MyRequest struct { http.Request PathParams map[string]string }
To initialize MyRequest, we need to set the values for its embedded http.Request struct. Here's how it can be done:
func New(origRequest *http.Request, pathParams map[string]string) *MyRequest { req := new(MyRequest) req.PathParams = pathParams req.Request = origRequest return req }
In this approach, we first create a new MyRequest object and assign it to req. We then set the PathParams field accordingly. Subsequently, we access and set the embedded http.Request struct by referencing req.Request.
Alternatively, we can also initialize the embedded struct using the following syntax:
req := &MyRequest{ PathParams: pathParams Request: origRequest }
Here, we create an anonymous struct with the required fields. It is important to prefix the embedded struct name with '&' for proper initialization. This results in a MyRequest object with the desired values.
Both approaches effectively initialize the embedded http.Request struct within MyRequest, allowing you to customize and use it as needed. For further reference, consult the Go specification on named fields for embedded structs.
The above is the detailed content of How to Initialize an Embedded Struct in Go: A Two-Approach Guide. For more information, please follow other related articles on the PHP Chinese website!