Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)
Explain Interfaces in Go: Empty Interface (`any`), Duck Typing, and `iface` vs. `eface` Representation.
senior LevelCode ExampleTypeScript
In Simple Words:
Interfaces in Go are satisfied implicitly: if a struct implements all methods of an interface, it implements the interface automatically without any implements keyword (Duck typing).
Under the hood, interfaces are two-word fat pointers:
iface(Interface with methods):tab: Pointer toitabcontaining the concrete type descriptor and function pointers.data: Pointer to the concrete value.
eface(Empty interface /any):_type: Pointer to the type definition.data: Pointer to the concrete value.
The nil Interface Trap:
An interface is only nil if BOTH its type pointer and data pointer are nil. An interface containing a non-nil type pointer pointing to a nil struct pointer is NOT nil!
go
type Greeter interface {
Greet() string
}
type MyError struct{}
func (e *MyError) Error() string { return "custom error" }
func getError() error {
var err *MyError = nil
return err // Returns iface{type: *MyError, data: nil} != nil !
}
func main() {
if getError() != nil {
// THIS EXECUTES! Because interface type is *MyError, not nil!
}
}