Golang / GoLang Basics Interview Questions
How do interfaces work in Go? How do you use type assertions and type switches?
An interface specifies a set of method signatures. Any type that implements all the methods satisfies the interface — implicitly, with no declaration. This is sometimes called structural typing or duck typing with static checking.
// Interface definition type Shape interface { Area() float64 Perimeter() float64 } // Circle satisfies Shape â no 'implements' keyword needed type Circle struct{ Radius float64 } func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius } func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius } type Rectangle struct{ W, H float64 } func (r Rectangle) Area() float64 { return r.W * r.H } func (r Rectangle) Perimeter() float64 { return 2 * (r.W + r.H) } // Polymorphic function â accepts any Shape func printShape(s Shape) { fmt.Printf("Area=%.2f Perimeter=%.2f\n", s.Area(), s.Perimeter()) } shapes := []Shape{Circle{5}, Rectangle{4, 6}} for _, s := range shapes { printShape(s) } // Type assertion â extract concrete type (safe form) var s Shape = Circle{Radius: 3} c, ok := s.(Circle) if ok { fmt.Println("radius:", c.Radius) } // radius: 3 // Type switch â check and handle multiple types switch v := s.(type) { case Circle: fmt.Printf("circle r=%.1f\n", v.Radius) case Rectangle: fmt.Printf("rect %.0fx%.0f\n", v.W, v.H) default: fmt.Println("unknown shape") } // Compile-time interface check (zero-cost assertion) var _ Shape = Circle{} // COMPILE ERROR if Circle doesn't implement Shape
More Related questions...