typestar

Type assertions in Go

Pulling a concrete type back out, safely or with a panic.

type Closer interface{ Close() error }

type File struct{ name string }

func (f File) Close() error { return nil }

func assertions(value any) (int, bool, bool) {
    number, ok := value.(int)

    _, isCloser := value.(Closer)

    defer func() { _ = recover() }()
    forced := value.(string) // panics unless it is a string
    return number + len(forced), ok, isCloser
}

How it works

  1. The two-result form never panics: check the bool.
  2. The one-result form panics when the type is wrong.
  3. Asserting to an interface asks whether extra methods exist.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
355
Tokens
94
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 54 seconds.

Type this snippet

Step 2 of 2 in Dynamic types, step 9 of 19 in Interfaces & generics.

← Previous Next →