0PricingLogin
Go Academy · Lesson

Type Assertions and Type Switches

Safe type assertions and switch patterns

Type Assertions

A type assertion extracts the concrete value from an interface. The syntax is x.(T):

package main
import "fmt"

func main() {
    var i interface{} = "hello"
    s := i.(string)          // panics if wrong type
    fmt.Println(s, len(s))   // hello 5
}

Safe Two-Value Assertion

Use the comma-ok form to avoid panics on wrong types:

package main
import "fmt"

func main() {
    var i interface{} = 42
    s, ok := i.(string)
    fmt.Println(s, ok)  // "" false
    n, ok := i.(int)
    fmt.Println(n, ok)  // 42 true
}

All lessons in this course

  1. Defining and Implementing Interfaces
  2. Core Standard Library Interfaces
  3. Type Assertions and Type Switches
  4. Interface Composition and Best Practices
← Back to Go Academy