Golang Interfaces: Optional Functions

examples -/
garage -/
car.go
bmx.go
ford.go
main.go
#garage/car.gopackage garage

type Car interface {
Drive()
}

type Options interface {
honk()
}

func Honk(car Car) {
# checks if this car has the honk option then executes
if carWithOptions, ok := car.(Options); ok {
carWithOptions.honk()
} else {
println("not implemented")
}
}
#garage/ford.go
package
garage

type Ford struct {
Name string
}

func (Ford) Drive(){
println("ford is driving")
}

func (Ford) honk() {
println("HONK!!!")
}
# garage/bmx.go
package
garage

type Bmx struct {
Name string
}

func (Bmx) Drive(){
println("bmx is cycling")
}
#main.go
package main
import (
"fmt"
"examples/garage"
)
# Need to use the car interfaces function Honk to handle the optional honk() function
func main() {
ford := garage.Ford{"Ford"}
ford.Drive()
garage.Honk(ford)
bmx := garage.Bmx{"Bmx"}
bmx.Drive()
garage.Honk(bmx)
}
ford is driving
HONK!!!
bmx is cycling
not implemented

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store