2 ms·
If you are satisfied with a dummy method on an interface, you can continue by adding more types to that interface. Color is not a great example, so: type V
by jerf 3y ago
If you are satisfied with a dummy method on an interface, you can continue by adding more types to that interface. Color is not a great example, so:
type Vehicle interface {
isVehicle()
}
type Car struct {}
func (c Car) isVehicle() {}
type Van struct {}
func (v Van) isVehicle() {}
func VehicleType(vehicle Vehicle) {
switch v := vehicle.(type) {
case Car:
fmt.Println("car")
case Van:
fmt.Println("van")
default:
fmt.Println("unknown vehicle")
}
This covers most, but not all, of the bases, in that you don't get exhaustiveness checking at compile time, unless you adjoin a linter to your compile process: https://github.com/BurntSushi/go-sumtype https://github.com/BurntSushi/go-sumtype
- jchw 3y agoYeah, I've done that before. It's not really elegant in my opinion, but OTOH, it's basically the best you can do. Oh well.