Patrick Kelly
1 min readDec 8, 2017

--

Go totally has a method_exists() solution. It’s done with defining an interface and then doing a type assertion.

Here’s some sample code:

type HasColorMethod interface {
Color() string
}
func PrintColor(thing interface{}) {
if c, ok := thing.(HasColorMethod); ok {
fmt.Println(c.Color())
} else {
fmt.Println("missing color method")
}
}

You can see/run an example here.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Patrick Kelly
Patrick Kelly

Written by Patrick Kelly

Web/database engineer/gopher. Cycling, photos, yada, yada.

No responses yet

Write a response