Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 147 ยท Interfaces

Type Assertions and Type Switches

Learn Go type assertions and type switches - the x.(T) forms, the comma-ok idiom, panics, multi-type cases, nil handling and the optional interface upgrade pattern.

An interface value hides the concrete type stored inside it. That is the whole point of interfaces: code that accepts a Shape does not care whether it got a circle or a square. But sometimes you do need to look inside. A function receives an any and must treat integers and strings differently. A Reader might also be a Closer, and you would like to close it when you can. A decoded JSON document is a tree of any values that you have to walk.

Go gives you two tools for this: the type assertion x.(T), which asks "is the value inside x a T?", and the type switch, which asks the same question for several types at once. This lesson covers both, including the forms that panic, the forms that do not, what happens with nil, and the interface upgrade pattern the standard library uses to add optional features without breaking old code.

The type assertion x.(T)

A type assertion has the form x.(T), where x is an interface value and T is a type. It does not convert anything. It checks the dynamic type (the concrete type stored in the interface) and, if it matches, gives you that value with static type T:

Go Asserting a concrete type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Before the assertion, the compiler only knows value is an any, so you cannot call len(value) or use string methods. After value.(string), text is an ordinary string.

When the assertion is wrong, it panics

The single-result form x.(T) panics if x does not hold a T. The message names both types, which makes it easy to diagnose:

Go A failing assertion panics (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The program prints before, then dies with panic: interface conversion: interface {} is string, not int, followed by a goroutine trace that points at main.go:9. The line after never runs. Use the single-result form only when a wrong type means a bug in your program, the same way you would not guard against an out-of-range constant index.

The comma-ok form

When the type is genuinely uncertain, ask for two results. The second is a bool that reports whether the assertion held, and nothing panics:

Go The comma-ok form never panics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

When the assertion fails, ok is false and the first result is the zero value of T (0 for int, "" for string). That is why you should always look at ok before using the value. The if v, ok := ...; ok shape from if, else if and else keeps n and s scoped to the branch that proves they are valid.

Name the boolean ok. It is the same idiom you meet with map lookups (v, ok := m[k]) and channel receives, so readers recognize it instantly.

Asserting to an interface type

T does not have to be a concrete type. If T is an interface, the assertion checks whether the dynamic type implements T, and the result has the static type T. This is how you ask "can this value do something extra?":

Go Asking whether a value has a method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Celsius has a String method, so it satisfies fmt.Stringer. The integer does not either. Plain strings and slices have no methods at all, so they fall through to the plain branch too. Note that nothing about Celsius mentions Stringer: satisfaction is implicit, so the check is purely about the method set.

Impossible assertions are compile errors

If x has a non-empty interface type, the compiler knows which methods the dynamic type must have, and it rejects assertions that could never succeed:

Go An impossible assertion (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports ./main.go:13:7: impossible type assertion: r.(Circle) and adds that Circle does not implement io.Reader (missing method Read). With any there is no such check, because every type implements the empty interface.

Type switches

A chain of if v, ok := x.(A); ok { } else if ... gets noisy fast. The type switch is the same check in the shape of a switch. The syntax is switch v := x.(type), where the literal keyword type stands in for the type in the assertion:

Go A type switch with several cases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Inside each case, x has the type named in that case, so x+1 works for int and x.Seconds() works for time.Duration. In the default branch x keeps the original interface type (any). Cases are tried from top to bottom, and cases may be interface types, like error above, which matches any value with an Error() string method.

Unlike an expression switch, a type switch has no fallthrough, and the cases cannot be constants. Two practical details:

  • If you do not use x in any branch, drop the binding and write switch v.(type). If you declare x but never use it in any clause, the compiler reports x declared and not used.
  • Order matters when a value matches several cases, such as a concrete type and an interface it implements. The first match wins.

Several types in one case

You can list multiple types in one case. Because the compiler cannot know which one matched, the variable then keeps the type of the switch expression:

Go Multiple types per case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In the first two cases x is an any, so %T still reports the real dynamic type. If you need arithmetic, split the cases; for numbers, generics with constraints are often the better tool.

nil and type switches

What does an interface that holds nothing do? A nil interface value has no dynamic type, so every assertion to a concrete type fails, and the comma-ok form reports false. In a type switch you can match it explicitly with case nil:

Go Handling nil in a type switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The two "nils" are different things. empty has no type at all and matches case nil. np is a typed pointer whose value happens to be nil; the interface holds the pair (*int, nil), so it matches case *int. This distinction causes a famous bug, which Interface Internals and the nil Trap dissects.

The single-result assertion on a nil interface also panics: var v any; _ = v.(int) fails with interface conversion: interface is nil, not int. Use comma-ok whenever nil is possible.

The interface upgrade pattern

Here is the most important design use of assertions. Suppose your function accepts an io.Writer. Some writers can do something smarter than Write. For instance, io.StringWriter offers WriteString, which avoids converting a string to a []byte first. Rather than demanding the bigger interface from everyone, you accept the small one and upgrade when the extra capability is present:

Go Using an optional interface when it exists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

counting only has Write, so the assertion fails and emit takes the fallback. fancy also has WriteString, so it gets the fast path. Callers never had to know. The standard library does this everywhere: io.Copy checks for io.WriterTo and io.ReaderFrom, fmt checks for fmt.Formatter and fmt.Stringer, and net/http checks whether a ResponseWriter is also an http.Flusher.

The pattern works because adding a method to a type never breaks code that did not know about it. If io.Writer itself had been changed to require WriteString, every existing writer would have stopped compiling.

You can also assert to an inline anonymous interface for a one-off check: if c, ok := r.(interface{ Close() error }); ok { c.Close() }. Reach for a named interface when the check appears in more than one place.

Assertions versus alternatives

Type assertions are a sign that the static types ran out of information. Sometimes that is correct (decoding JSON into any, walking an AST, the upgrade pattern). Often it is a hint to use something else:

  • If you assert on a closed set of your own types, consider adding a method to the interface and letting each type do its own work. That is polymorphism, and the compiler checks it for you.
  • If the set of types is a numeric family, a generic function keeps the static type instead of discarding it.
  • A type switch is the right tool when the set of types is open-ended or comes from outside your code, such as the values produced by the empty interface.
  • A type switch on error values is usually better written with errors.As, which also looks through wrapped errors (see Wrapping and Inspecting Errors).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when this runs?

    var v any = 3.5; n := v.(int); fmt.Println(n)

    The single-result assertion panics when the dynamic type is not the asserted one. v holds a float64, so v.(int) panics. It compiles because v is an any.
  2. 2. What does n, ok := v.(int) give when v holds the string "hi"?

    The comma-ok form never panics. On failure it returns the zero value of the asserted type and false.
  3. 3. In switch x := v.(type) { case int, string: ... }, what is the static type of x inside that case?

    With more than one type in a case, the compiler cannot pick one, so x keeps the type of the switch expression.
  4. 4. Which case matches an interface variable that holds nothing at all?

    A nil interface has no dynamic type; case nil matches it. (default also runs if there is no nil case, but case nil is the explicit match.)
  5. 5. Why does the interface upgrade pattern check w.(io.StringWriter) instead of requiring it in the function signature?

    Accepting the small interface keeps the function usable by all writers, while the optional assertion lets capable writers be used more efficiently.

Summary

  • x.(T) checks the dynamic type of interface value x; it yields a T on success and panics on failure.
  • v, ok := x.(T) never panics: on failure v is the zero value and ok is false.
  • When T is an interface, the assertion checks whether the dynamic type implements it; with non-empty interfaces the compiler rejects impossible assertions.
  • A type switch (switch v := x.(type)) tries cases top to bottom; v has the case's type, or the interface type when a case lists several types or is default.
  • case nil matches an interface with no dynamic type, which is different from an interface holding a nil pointer.
  • The interface upgrade pattern accepts a small interface and asserts for optional capabilities such as io.StringWriter.
  • Prefer methods, generics and errors.As when they fit; use assertions when types are open-ended or come from outside.

Next: Common Standard Interfaces tours the interfaces you will implement most often.