Home  >  Article  >  Backend Development  >  How Can You Initialize an Embedded Struct Field Using an Existing Instance in Go?

How Can You Initialize an Embedded Struct Field Using an Existing Instance in Go?

DDD
DDDOriginal
2024-11-12 06:03:02944browse

How Can You Initialize an Embedded Struct Field Using an Existing Instance in Go?

Issues Encountered with Embedded Struct Initialization 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"?
}

Solution

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.

Understanding Embedded Struct Field Naming

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn