Type assertion

When an interface (empty or otherwise) is assigned to a variable, it carries type information that can be queried at runtime. Type assertion is a mechanism that is available in Go to idiomatically narrow a variable (of interface type) down to a concrete type and value that are stored in the variable. The following example uses type assertion in the eat function to select which food type to select in the eat function:

type food interface { eat() } type veggie string func (v veggie) eat() { fmt.Println("Eating", v) } type meat string func (m meat) eat() { fmt.Println("Eating tasty", m) } func eat(f food) { veg, ok := f.(veggie) if ok { if veg == "okra" { fmt.Println("Yuk! not eating ", veg) }else{ veg.eat() } return } mt, ok := f.(meat) ...

Get Learning Go Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.