Goにおける構造体埋め込みの理解
Olivia Novak
Dev Intern · Leapcell

Key Takeaways
- Struct embedding allows for field and method promotion, enabling code reuse without traditional inheritance.
- Methods of embedded structs can be accessed directly and even overridden in the outer struct.
- Embedding promotes Go’s composition-over-inheritance philosophy for flexible and maintainable code.
Goプログラミングにおいて、構造体埋め込みは、開発者が柔軟かつ再利用可能な方法で型を構成できる強力な機能です。ある構造体を別の構造体の中に埋め込むことで、埋め込まれた構造体のフィールドとメソッドを外側の構造体に昇格させ、コードの再利用とより複雑なデータ構造の作成を促進できます。
What is Struct Embedding?
Goの構造体埋め込みは、ある構造体が別の構造体に含まれる構成の一形態です。他のプログラミング言語にある従来の継承とは異なり、Goの埋め込みは、埋め込まれた構造体のフィールドとメソッドを包含する構造体に昇格させます。これは、外側の構造体が、埋め込まれた構造体のフィールドとメソッドを、あたかもそれが自身のもののように直接アクセスできることを意味します。
How to Embed Structs in Go
ある構造体を別の構造体の中に埋め込むには、外側の構造体でフィールド名を付けずに、埋め込む構造体の型を単純に宣言します。以下に例を示します。
package main import "fmt" // Define a base struct type Person struct { Name string Age int } // Define another struct that embeds Person type Employee struct { Person EmployeeID string } func main() { // Initialize an Employee instance e := Employee{ Person: Person{ Name: "Alice", Age: 30, }, EmployeeID: "E12345", } // Access fields from the embedded Person struct fmt.Println("Name:", e.Name) // Output: Name: Alice fmt.Println("Age:", e.Age) // Output: Age: 30 fmt.Println("Employee ID:", e.EmployeeID) // Output: Employee ID: E12345 }
この例では、Employee構造体がPerson構造体を埋め込んでいます。その結果、EmployeeはPersonからフィールドNameとAgeを継承し、Employeeのインスタンスを通じてこれらのフィールドに直接アクセスできます。
Method Promotion with Embedded Structs
埋め込みは、埋め込まれた構造体のメソッドも外側の構造体に昇格させます。これにより、外側の構造体は、明示的な委譲なしに、埋め込まれた構造体で定義されたメソッドを呼び出すことができます。次の例を考えてみましょう。
package main import "fmt" // Define a base struct with a method type Person struct { Name string } func (p Person) Greet() { fmt.Println("Hello, my name is", p.Name) } // Define another struct that embeds Person type Employee struct { Person EmployeeID string } func main() { // Initialize an Employee instance e := Employee{ Person: Person{ Name: "Bob", }, EmployeeID: "E67890", } // Call the Greet method from the embedded Person struct e.Greet() // Output: Hello, my name is Bob }
ここで、Person構造体で定義されたGreetメソッドは、埋め込みを通じてEmployee構造体に昇格されます。これにより、EmployeeインスタンスはGreetメソッドを直接呼び出すことができます。
Overriding Embedded Methods
外側の構造体が、埋め込まれた構造体と同じ名前のメソッドを定義する場合、外側の構造体のメソッドが埋め込まれたメソッドをオーバーライドします。以下に例を示します。
package main import "fmt" // Define a base struct with a method type Person struct { Name string } func (p Person) Greet() { fmt.Println("Hello, my name is", p.Name) } // Define another struct that embeds Person and overrides Greet type Employee struct { Person EmployeeID string } func (e Employee) Greet() { fmt.Println("Hello, I am employee", e.EmployeeID) } func main() { // Initialize an Employee instance e := Employee{ Person: Person{ Name: "Charlie", }, EmployeeID: "E54321", } // Call the overridden Greet method e.Greet() // Output: Hello, I am employee E54321 // Call the original Greet method from Person e.Person.Greet() // Output: Hello, my name is Charlie }
この場合、Employee構造体は、埋め込まれたPerson構造体のGreetメソッドをオーバーライドする独自のGreetメソッドを定義します。ただし、埋め込まれた構造体の名前(e.Person.Greet())で修飾することで、元のGreetメソッドにアクセスできます。
Conclusion
Goの構造体埋め込みは、コードの再利用と柔軟性を促進する型の構成のメカニズムを提供します。構造体を埋め込むことで、明示的な継承を必要とせずに、他の構造体からフィールドとメソッドを継承する複雑なデータ構造を作成できます。この機能は、Goのシンプルさと構成可能性という設計理念に沿っており、開発者は堅牢で保守可能なアプリケーションを構築できます。
FAQs
Struct embedding is a way to include one struct within another, allowing field and method promotion.
Yes, the outer struct can define a method with the same name, overriding the embedded one.
Use the embedded struct's name, e.g., e.Person.Greet(), to call its original method.
We are Leapcell, your top choice for hosting Go projects.
Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
- Develop with Node.js, Python, Go, or Rust.
Deploy unlimited projects for free
- pay only for usage — no requests, no charges.
Unbeatable Cost Efficiency
- Pay-as-you-go with no idle charges.
- Example: $25 supports 6.94M requests at a 60ms average response time.
Streamlined Developer Experience
- Intuitive UI for effortless setup.
- Fully automated CI/CD pipelines and GitOps integration.
- Real-time metrics and logging for actionable insights.
Effortless Scalability and High Performance
- Auto-scaling to handle high concurrency with ease.
- Zero operational overhead — just focus on building.
Explore more in the Documentation!
Follow us on X: @LeapcellHQ



