Home > Article > Backend Development > How Can You Initialize an Embedded Struct Field Using an Existing Instance in Go?
Embedded structs offer significant advantages in Go, but they can sometimes present unique challenges, particularly during initialization. Consider the following scenario, where a struct containing an anonymous inner struct must be initialized using an existing instance of the inner struct.
type MyRequest struct { Request http.Request PathParams map[string]string } func New(origRequest *http.Request, pathParams map[string]string) *MyRequest { // How to initialize "Request" field with "origRequest"? }
To address this problem, there are two viable options:
Option 1:
req := new(MyRequest) req.PathParams = pathParams req.Request = *origRequest
In this approach, a new instance of MyRequest is created using new. The PathParams field is initialized with the provided pathParams map. The anonymous inner struct Request is initialized by explicitly assigning the dereferenced value of origRequest to it.
Option 2:
req := &MyRequest{ PathParams: pathParams, Request: origRequest, }
This alternative approach uses a composite literal syntax to create a new instance of MyRequest. Both the PathParams and Request fields are initialized within the literal. It's important to note that the Request field is initialized without the need for dereferencing.
When an anonymous inner struct is embedded within a larger struct, the embedded fields inherit the name of the outer struct. In this case, both PathParams and Request become fields of MyRequest. For more information, refer to the Go specification on [Struct Types](https://go.dev/ref/spec#Struct_types).
The above is the detailed content of How Can You Initialize an Embedded Struct Field Using an Existing Instance in Go?. For more information, please follow other related articles on the PHP Chinese website!