liveBook · Manning

Type assertion

As explained in Go by Example

A runtime type assertion is a Go expression that checks and retrieves the concrete value represented by an interface value at run time.

A type assertion checks whether an interface value’s concrete value has a requested type or behavior. The comma-ok form lets code use optional capabilities safely: when the assertion fails, the boolean is false and the capability is skipped rather than called. section 9.4.1

Flush only when supported

An HTTP handler can treat http.ResponseWriter as the common interface, then assert it to http.Flusher before calling Flush. This preserves a simple handler API while allowing compatible response writers to stream buffered data immediately. section 9.4.1

func MyHandler(w http.ResponseWriter, r *http.Request) {
  if flusher, ok := w.(http.Flusher); ok {  #1
    flusher.Flush()  #2
  }
}

The handler asserts the response writer to http.Flusher, checks ok, and calls Flush only on implementations that provide it. section 9.4.1

Assertions are especially useful around wrappers and embedded interfaces. Embedding ResponseWriter promotes only its declared methods; optional methods on the original concrete writer can become hidden. A wrapper can expose an Unwrap method so callers can recover the original writer and inspect its optional interfaces. section 9.4.1 section 9.8

They also recover typed values from deliberately general APIs. Context.Value returns any, so a trace-ID helper asserts the result to string and returns both the value and success flag. Similarly, a SQL Scanner can assert an incoming database value to string before decoding it, returning an error when the type is unsuitable. section 9.5.1 section 10.3.2

Use assertions to extend behavior without tightening the main interface:

  • Detect small optional interfaces such as flushing, server push, connection hijacking, or driver features. section 9.4.1 section 10.1
  • Keep assertions at boundaries where dynamic values enter code, such as Context values and Scanner inputs. section 9.5.1 section 10.3.2
  • Prefer wrapping and small optional interfaces over expanding a widely used interface, which can break existing implementations. section 9.11 section 10.1

Type assertions support Go’s composition style: code depends on a focused interface for ordinary work, then discovers extra behavior only where it matters. This keeps APIs stable and lets wrappers, handlers, and database abstractions add features without requiring every implementation to change. section 9.0 section 10.1

How Go by Example covers it

How deep it goes
Demonstrates comma-ok checks, wrapper unwrapping, Context extraction, and Scanner validation without detailing assertion runtime internals.
Examples
Uses http.Flusher on ResponseWriter, trace IDs stored in Context, and a base64 SQL Scanner.
What it assumes
Assumes familiarity with interfaces and embedding while introducing assertions through optional interface examples.
What you can do after
Apply it via Go interfaces to safely invoke optional capabilities and validate dynamically typed boundary values.
How it connects
Connects interfaces, embedding, wrapping, Context, HTTP handlers, database/sql, and composition.

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 Go by Example. The section links point to the parts of the book it draws on.