Golang / GoLang Interfaces and Object Oriented Interview Questions
What is an interface in Go and how does it differ from interfaces in Java or C#?
In Go, an interface is a named set of method signatures. Any concrete type that implements all the methods in the set automatically satisfies the interface — no declaration, no implements keyword, no registration is required. This property is called implicit (or structural) interface satisfaction.
In Java or C#, a class must explicitly declare that it implements an interface (class Dog implements Animal). In Go, the relationship is inferred entirely by the compiler from the method set of the concrete type. This decoupling means interfaces and implementations can live in completely separate packages with no dependency between them.
// Define an interface
type Writer interface {
Write(p []byte) (n int, err error)
}
// os.File satisfies Writer — it has the right Write method
// No 'implements Writer' anywhere in the os package
var w Writer = os.Stdout // compiles because *os.File has Write([]byte)(int,error)
// Your own type
type NullWriter struct{}
func (NullWriter) Write(p []byte) (int, error) { return len(p), nil }
var w2 Writer = NullWriter{} // also satisfies Writer implicitly| Aspect | Go | Java / C# |
|---|---|---|
| Satisfaction | Implicit — compiler infers from method set | Explicit — 'implements' / ':' required |
| Coupling | Zero coupling between interface and type | Type must know about the interface |
| Retroactive satisfaction | Any type can satisfy any interface, even in other packages | Not possible without modifying the class |
| Zero-method interface | interface{} / any — satisfied by everything | Object — every class descends from it |
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...
