Golang / GoLang Interfaces and Object Oriented Interview Questions
Summarise the key rules and best practices for Go interfaces that interviewers test.
This summary covers the most frequently tested interface rules in Go technical interviews:
| Rule | Detail |
|---|---|
| Implicit satisfaction | No 'implements' keyword — matching method set is sufficient |
| Method set (value) | T has only value-receiver methods in its method set |
| Method set (pointer) | *T has both value AND pointer receiver methods |
| Nil interface | Both type and data words must be zero — interface nil |
| Nil pointer in interface | Type word non-zero → interface NOT nil — classic trap |
| Return nil, not typed nil | Functions returning error must use bare 'nil', never (*MyError)(nil) |
| Two-word layout | word1=itab (type+dispatch table), word2=data pointer |
| Interface comparison | Equal iff same dynamic type AND same dynamic value (panics on non-comparable) |
| Empty interface (any) | interface{} — all types satisfy it; loses compile-time type safety |
| Interface composition | Embed interfaces to build larger contracts |
| Accept interfaces | Function parameters should be interfaces — enables mocking and flexibility |
| Return concrete | Constructors return concrete types — gives callers full method set |
| Compile-time check | var _ MyInterface = (*MyType)(nil) — asserts satisfaction at compile time |
| Small interfaces | 1–3 methods; 'bigger interface = weaker abstraction' |
| Interface ownership | Define interface in the consuming package, not the producing package |
// Quick reference â most tested patterns // 1. Compile-time check var _ io.Writer = (*MyWriter)(nil) // 2. Return nil correctly func f() error { return nil } // NOT: var e *MyError; return e // 3. Comma-ok assertion (never panic) if w, ok := v.(io.Writer); ok { w.Write(data) } // 4. Type switch switch t := v.(type) { case int: use(t) case string: use(t) default: unknown(t) } // 5. Nil interface check var r io.Reader // nil if r != nil { r.Read(buf) } // safe // 6. Non-nil interface with nil data var p *bytes.Buffer var w io.Writer = p // w != nil even though p == nil // 7. Consumer-defined narrow interface type Saver interface { Save() error } // in consumer package // 8. Interface upgrade (optional capability) if sw, ok := w.(io.StringWriter); ok { sw.WriteString(s) }
What is the method set of a value of type T when T has both value receiver methods (A) and pointer receiver methods (B)?
Which of the following is the correct way to return 'no error' from a function returning the error interface?
More Related questions...