Type assertions
A type assertion x.(T) says that the value in interface x has dynamic type T (or a type that satisfies interface T). The comma-ok form returns a bool instead of panicking when it does not.
Detailed Explanation
You have an error or an any and you need the concrete value. pe := err.(*os.PathError) asks "is this a *os.PathError?" If yes, pe is that pointer. If no, the one-result form panics. The two-result form pe, ok := err.(*os.PathError) sets ok to false and pe to nil (or the zero of T).
T can be a concrete type or an interface. x.(*File) extracts a pointer. x.(io.Reader) succeeds when the dynamic type has Read. The result's static type is T. Asserting to an interface does not copy the value out of the box; it produces another interface with a possibly smaller method set.
The one-result form is a panic waiting for a surprise. Use it only when a failed assertion is a programmer bug — you just stored a *File and you are reading it back on the next line. At a process boundary (JSON, plugins, recover values), use comma-ok or a type switch.
Assertions do not wrap. err.(*os.PathError) looks at the outermost dynamic type. A wrapped error will fail the assertion even if the cause is a *os.PathError. Use errors.As for errors. Assertions remain correct for any values that are not error chains.
x.(type) is a type switch, not an assertion. You cannot write t := x.(type) outside switch. The switch is the multi-way form of the same idea.
What it costs. An assertion is a compare of the dynamic type word (and, for interface targets, a method-set check). It is cheap. A panic from the one-result form is not cheap, and it is a crash. Prefer comma-ok in library code.
Code Examples
package main
import "fmt"
func asString(v any) (string, bool) {
s, ok := v.(string)
return s, ok
}
func main() {
s, ok := asString("shop")
fmt.Println(s, ok)
_, ok = asString(3)
fmt.Println(ok)
}func mustInt(v any) int {
return v.(int) // panics if v is not int
}func asReader(v any) (io.Reader, bool) {
r, ok := v.(io.Reader)
return r, ok
}Common Gotchas
`v.(T)` panics on mismatch
always use `v, ok :=` when `v` came from outside your function.
Asserting a non-interface value does not compile
`n.(int)` is illegal if `n` is already `int`. The left side must be an interface.
Wrapped errors fail concrete assertions
`errors.As` walks the chain; `err.(*T)` does not.
A failed comma-ok assertion zeros the result
do not use the value when `ok` is false.