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, WORLDThe 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
