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

Susan Sarandon
Release: 2024-11-17 15:44:02
Original
308 people have browsed it

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
}
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template