"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Initialize an Embedded Struct in Go: A Two-Approach Guide

How to Initialize an Embedded Struct in Go: A Two-Approach Guide

Posted on 2025-03-22
Browse:760

How to Initialize an Embedded Struct in Go: A Two-Approach Guide

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3