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




