liveBook · Manning

Type assertion

As explained in Build and Orchestrator in Go (From Scratch)

A type assertion is a Go operation that extracts a value of a specified concrete or interface type from an interface value.

A type assertion extracts a value of a specified concrete or interface type from an interface value. It matters when an interface-based API hides the concrete value needed for updates or further processing. In a store, a retrieved interface value can be asserted as a pointer to task.Task before its fields are changed. section 11.5 section 11.3

Retrieving and updating a task

result, err := m.TaskDb.Get(t.ID.String()) if err != nil { log.Printf("%s", err) continue } taskPersisted, ok := result.(*task.Task) if !ok { log.Printf("cannot convert result to task.Task") continue } taskPersisted.State = t.State m.TaskDb.Put(taskPersisted.ID.String(), taskPersisted)

How Build and Orchestrator in Go (From Scratch) covers it

How deep it goes
Explains the two-result assertion, its ok check, and failure handling, but does not descend into runtime representation internals.
Examples
Demonstrates assertions while storing, retrieving, updating, listing, and processing task and task-event values.
What it assumes
Assumes familiarity with Go interfaces, pointers, methods, and error returns while demonstrating interface-to-concrete conversion in context.
What you can do after
Diagnose/debug with it by checking ok and returned errors before using an interface value as its expected concrete type.
How it connects
Connects type assertions with interfaces, empty interfaces, pointers, comma-ok checks, error handling, and in-memory stores.

Also explained in

Compare how 5 books explain type assertion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build and Orchestrator in Go (From Scratch). The section links point to the parts of the book it draws on.