liveBook · Manning

Struct embedding

As explained in Learn Go with Pocket-Sized Projects

Embedding is a Go struct feature that incorporates an unnamed field's type and promotes its methods and fields to the containing type.

Struct embedding is an unnamed field that incorporates another type into a Go struct. The containing type can use the embedded type’s methods and fields, giving composition an inheritance-like feel without an inheritance system. section 1.2.1 section 10.2.2

Embedding a generated gRPC server

A gRPC server embeds the generated implementation to satisfy a required interface method while adding its own dependencies and endpoints: ```go type Server struct { api.UnimplementedHabitsServer lgr Logger } func (s *Server) CreateHabit( _ context.Context, request *api.CreateHabitRequest, ) (*api.CreateHabitResponse, error) { s.lgr.Logf("CreateHabit request received: %s", request) return &api.CreateHabitResponse{ Habit: &api.Habit{}, }, nil } ``` The embedded `UnimplementedHabitsServer` supplies the required `mustEmbedUnimplementedHabitsServer` method, allowing `Server` to register as a `HabitsServer`. section 10.2.2

// Server is the implementation of the gRPC server.
type Server struct {
    api.UnimplementedHabitsServer
    lgr Logger
}

Inspect the compact server definition that combines an embedded generated service with a named logger field. section 10.2.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines embedding through a server example and explains its required generated method, but does not explore method promotion mechanics in depth.
Examples
Uses Server, UnimplementedHabitsServer, Logger, and CreateHabit to demonstrate embedded and named fields together.
What it assumes
Assumes familiarity with Go structs and interfaces while demonstrating the generated service method requirement directly.
What you can do after
Build it from scratch by embedding a generated implementation and registering the containing server against its interface.
How it connects
Connects embedding with composition, implicit interfaces, inheritance, structs, and gRPC service interfaces.

Also explained in

Compare how 4 books explain struct embedding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.