Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the compile-time interface check idiom and why is it important?
Because Go interface satisfaction is implicit, the compiler normally checks it only at the point of actual use (assignment or function call). If a type is exported and expected to satisfy an interface, a change to the type's method set might silently break the contract — only catching the error at the site of use, not at the site of definition.
The compile-time check idiom prevents this:
// Idiom: assign nil pointer of the type to an interface variable
// This costs nothing at runtime (no allocation) but fails to compile
// if the interface is not satisfied.
type MyStore struct{ /* ... */ }
func (m *MyStore) Get(key string) (string, error) { /* ... */ return "", nil }
func (m *MyStore) Set(key, val string) error { /* ... */ return nil }
func (m *MyStore) Delete(key string) error { /* ... */ return nil }
type Cache interface {
Get(key string) (string, error)
Set(key, val string) error
Delete(key string) error
}
// Compile-time check — placed right after the type definition
var _ Cache = (*MyStore)(nil) // fails to compile if *MyStore doesn't satisfy Cache
// Alternatively, for value receivers:
var _ Cache = MyStore{} // check value type
// This check is also useful in test files:
// var _ http.Handler = (*MyHandler)(nil)
// var _ sort.Interface = ByAge(nil)
// What error you get on failure:
// cannot use (*MyStore)(nil) (type *MyStore) as type Cache in assignment:
// *MyStore does not implement Cache (missing Delete method)The idiom is especially important for exported types in libraries: the check serves as documentation ("this type is intended to implement Cache") and as a regression guard. If a developer accidentally removes a method or changes its signature, the check immediately fails with a clear error pointing to the problem.
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...
