Skip to main content
InterviewHubPRO
Section Overview
Q6

Question 6 of 50

Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)

12%
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:

  1. iface (Interface with methods):
    • tab: Pointer to itab containing the concrete type descriptor and function pointers.
    • data: Pointer to the concrete value.
  2. 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!
	}
}