Back to Gotraining

README

topics/go/language/embedding/README.md

latest1.7 KB
Original Source

Embedding

Embedding types provide the final piece of sharing and reusing state and behavior between types. Through the use of inner type promotion, an inner type's fields and methods can be directly accessed by references of the outer type.

Notes

  • Embedding types allow us to share state or behavior between types.
  • The inner type never loses its identity.
  • This is not inheritance.
  • Through promotion, inner type fields and methods can be accessed through the outer type.
  • The outer type can override the inner type's behavior.

Methods, Interfaces and Embedded Types in Go - William Kennedy
Embedding is not inheritance - JBD

Code Review

Declaring Fields (Go Playground)
Embedding types (Go Playground)
Embedded types and interfaces (Go Playground)
Outer and inner type interface implementations (Go Playground)

Exercises

Exercise 1

Copy the code from the template. Add a new type CachingFeed which embeds Feed and overrides the Fetch method.

Template (Go Playground) | Answer (Go Playground)


All material is licensed under the Apache License Version 2.0, January 2004.