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 |
More Related questions...