Golang Interfaces: Optional Functions
1 min readAug 29, 2018
A simple set of code snippets that show you how to facilitate optional functions for interfaces and the structs that implement them
Folder Structure
examples -/
garage -/
car.go
bmx.go
ford.go
main.go
Car interface with an optional honk
function as an option for a car.
#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")
}
}
We’ll implement a Ford car that drives and honks
#garage/ford.go
package garage
type Ford struct {
Name string
}
func (Ford) Drive(){
println("ford is driving")
}
func (Ford) honk() {
println("HONK!!!")
}
Now we want to implement a bmx cycle that “drives” but does not have a horn to honk
# garage/bmx.go
package garage
type Bmx struct {
Name string
}
func (Bmx) Drive(){
println("bmx is cycling")
}
Imports garage lib and creates car objects to test.
#main.go
package mainimport (
"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)
}
Output when run:
ford is driving
HONK!!!
bmx is cycling
not implemented
For more of this type of content. Feel free to follow me here