Golang / GoLang Interfaces and Object Oriented Interview Questions
How do type assertions work on interface values and when do you use them?
A type assertion extracts the concrete value from an interface variable. There are two forms: the single-return form that panics on failure, and the comma-ok form that returns a boolean.
type Animal interface { Sound() string } type Dog struct{ Name string } func (d Dog) Sound() string { return "Woof" } var a Animal = Dog{Name: "Rex"} // Form 1: single return â panics if a does not hold a Dog d := a.(Dog) fmt.Println(d.Name) // Rex // Form 2: comma-ok â safe, never panics d2, ok := a.(Dog) if ok { fmt.Println(d2.Name) // Rex } // Wrong type â form 2 gracefully handles it type Cat struct{} func (Cat) Sound() string { return "Meow" } _, ok = a.(Cat) // ok = false â a holds Dog, not Cat // Interface-to-interface assertion â check if concrete type satisfies another interface type Namer interface{ Name() string } type NamedDog struct{ name string } func (n NamedDog) Sound() string { return "Woof" } func (n NamedDog) Name() string { return n.name } var a2 Animal = NamedDog{name: "Buddy"} if namer, ok := a2.(Namer); ok { fmt.Println("name:", namer.Name()) // name: Buddy } // Type switch â idiomatic multi-type dispatch func handleAnimal(a Animal) { switch v := a.(type) { case Dog: fmt.Println("Dog:", v.Name) case Cat: fmt.Println("Cat") case NamedDog: fmt.Println("NamedDog:", v.name) default: fmt.Printf("Unknown: %T\n", v) } }
The type switch (switch v := a.(type)) is the idiomatic way to handle multiple concrete types from an interface. In each case arm, v is already typed as the concrete type — no additional assertion needed. The default case handles any type not listed explicitly.
More Related questions...