Given the following struct Foo
and goal of handling multiple types (where Handle
could be Read
, Write
, etc.). I understand that we lose compile-time type checks when we use the empty interface, though aside from this, what are the pros and cons of each? Finally, what is the most idiomatic way to achieve this?
package main
type Foo struct {
A int
B string
}
//Handle all types with switch
func (f *Foo) Handle(obj interface{}) {
switch obj := obj.(type) {
case int:
//do int stuff...
f.A + obj
case string:
//do string stuff...
f.B + obj
default:
panic("Unknown type")
}
}
//Handle each type individually
func (f *Foo) HandleInt(i int) {
//do int stuff...
f.A + i
}
func (f *Foo) HandleString(s string) {
//do string stuff...
f.B + s
}