Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the function-as-interface pattern in Go and how does it enable flexible APIs?
Go allows you to declare a named function type and attach methods to it — making it satisfy an interface. This eliminates the need for a wrapper struct when the only state needed is the function itself. It is used extensively in net/http, testing, and plugin architectures.
// Define an interface type Transformer interface { Transform(s string) string } // Named function type type TransformFunc func(string) string // Implement the interface on the function type func (f TransformFunc) Transform(s string) string { return f(s) } // Usage: pass a closure directly func applyAll(s string, ts ...Transformer) string { for _, t := range ts { s = t.Transform(s) } return s } result := applyAll(" hello world ", TransformFunc(strings.TrimSpace), TransformFunc(strings.ToUpper), TransformFunc(func(s string) string { return "[" + s + "]" }), ) fmt.Println(result) // [HELLO WORLD] // Struct implementing the same interface â full control over state type PrefixTransformer struct{ Prefix string } func (p PrefixTransformer) Transform(s string) string { return p.Prefix + s } result2 := applyAll("world", PrefixTransformer{Prefix: "Hello, "}, TransformFunc(strings.ToUpper), ) fmt.Println(result2) // HELLO, WORLD
The pattern makes APIs flexible: callers can provide a simple closure or a stateful struct — both satisfy the interface. The API never needs to know which was used. This is the basis of middleware chains, plugin hooks, and event callbacks in Go.
More Related questions...