liveBook · Manning

Type assertion

As explained in Go in Practice, Second Edition

A type assertion is a Go operation that retrieves the concrete value of an interface value when it has a specified dynamic type.

A type assertion checks whether an interface value satisfies a target interface and can retrieve the value in that interface form. Go uses interfaces to express shared method sets rather than inheritance, so assertions provide a direct runtime check alongside conversion. section 13.1.2

Check for fmt.Stringer

A helper can test arbitrary values with the two-result assertion `_, ok := v.(fmt.Stringer)`. A `bytes.Buffer` satisfies `fmt.Stringer`, while an integer does not; the boolean result lets the caller branch without treating the check as an unconditional conversion. section 13.1.2

Assertions also appear when retrieving typed values from context. A handler obtains `ctx.Value("webConfig").(config)` and uses the resulting configuration to build its response. This pattern shares request-related configuration without a global variable, though the surrounding example also exposes a discarded cancellation function that go vet reports. section 6.1.2

Listing 13.4 Checking and converting a type
package main

import (
     "bytes"
     "fmt"
)

func main() {
     b := bytes.NewBuffer([]byte("Hello"))
     if isStringer(b) {  #1
            fmt.Printf("%T is a stringer\n", b)
     }
     i := 123
     if isStringer(i) {   #2
            fmt.Printf("%T is a stringer\n", i)
     }
}

func isStringer(v interface{}) bool {   #3
     _, ok := v.(fmt.Stringer)          #3
     return ok
}

Browse the complete runnable example that checks interface satisfaction with a type assertion. section 13.1.2

How Go in Practice, Second Edition covers it

How deep it goes
Explains assertion syntax through runnable examples and contrasts it with reflection for interface types selected at runtime.
Examples
Demonstrates Stringer checks on a bytes.Buffer and integer, then retrieves web configuration from context in an HTTP handler.
What it assumes
Assumes familiarity with Go interfaces and methods, while illustrating interface satisfaction without inheritance declarations.
What you can do after
Apply it via Go's assertion syntax to test interface satisfaction and retrieve typed configuration from an interface value.
How it connects
Connects type assertions with interfaces, method sets, reflection, context, and go vet.

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 in Practice, Second Edition. The section links point to the parts of the book it draws on.