Home > Backend Development > Golang > How to Initialize Embedded Structs in Go?

How to Initialize Embedded Structs in Go?

Mary-Kate Olsen
Release: 2024-11-11 01:30:02
Original
595 people have browsed it

How to Initialize Embedded Structs in Go?

Understanding Embedded Struct Initialization in Go

Go provides the concept of embedding, allowing a struct to contain fields from another type without duplicating its implementation. In the context of embedded structs, initializing the anonymous inner struct becomes an essential task.

Initializing Anonymous Inner Struct in MyRequest

Consider the following code snippet, where the MyRequest struct embeds the http.Request struct:

type MyRequest struct {
    http.Request
    PathParams map[string]string
}
Copy after login

To initialize the anonymous inner struct, http.Request, in the New function, you can follow these approaches:

  • Using new keyword:
req := new(MyRequest)
req.PathParams = pathParams
req.Request = origRequest
Copy after login
  • Using struct literal syntax:
req := &MyRequest{
  PathParams: pathParams
  Request: origRequest
}
Copy after login

Both approaches achieve the same goal of initializing the http.Request field of the MyRequest struct with the provided origRequest parameter.

Reference

For a deeper understanding of embedding and field naming in structs, refer to the official Go documentation:

  • https://golang.org/ref/spec#Struct_types

The above is the detailed content of How to Initialize Embedded Structs in Go?. 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