O'Reilly logo

Go: Design Patterns for Real-World Projects by Mat Ryer, Mario Castro Contreras, Vladimir Vivien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required