Skip to main content
Module 5 · Lesson 3 of 523/50 in the course~12 min
Module lessons (3/5)

Composition (embedding)

Lesson preview5 hands-on exercises readyCourse Go · Module 5 — Structs and methods

In Go there is no inheritance: it is composed by embedding one type inside another. Promotion of methods.

What you'll learn in this lesson

  • Embedding a struct inside another via embedding (anonymous unlabeled field).
  • Take advantage of the automatic promotion of fields and methods on the external struct, disambiguating any collisions.
  • Distinguish when to prefer embedding (API delegation) versus an explicit named field (private composition).

Overview

Go has no classes or inheritance (extends): the reuse of data and behaviors is achieved by composing smaller structs inside other larger structs.

By inserting the name of a type inside the struct without assigning it a field name, the fields and methods of the built-in type are promoted directly to the outer level:

Sections covered in this lesson

  1. 1Struct embedding and promotion of methods and fields
  2. 2Shadowing, disambiguation and multiple embedding
  3. 3Nominated composition vs embedding
  4. 4Explicit shadowing vs named field encapsulation
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 5 — Structs and methods

Unlock "Composition (embedding)" and the full Course Go curriculum

In Go there is no inheritance: it is composed by embedding one type inside another. Promotion of methods.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Go plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.