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




