Coding/Learn/go/go interfaces and polymorphism
Go Foundational Course
01.Introduction, Toolchain & Package main
02.Variables, Zero Values, Constants & iota
03.Control Flow: If with Init Statements & Switch
04.The Unified For Loop & Range Iteration
05.Functions, Multiple Return Values & Named Returns
06.Arrays vs Slices: Dynamic Memory & Headers
07.Maps: Key-Value Hash Tables & Safe Access
08.Pointers & Value vs Pointer Semantics
09.Structs, Receiver Methods & Composition
10.Implicit Interfaces & Duck Typing with Typesafety
11.Explicit Error Handling, Wrapping & Inspection
12.Defer, Panic & Recover: Resource Cleanup
13.Strings, Runes & UTF-8 Encoding Internals
14.Goroutines & The M:N Work-Stealing Scheduler
15.Channels: CSP Concurrency & Pipelines
16.Select Statement, Non-Blocking IO & Timeouts
17.Mutexes, RWMutex & Atomic Primitives
18.Context Propagation, Cancellation & Deadlines
19.JSON Serialization, Tags & net/http Routing
20.Capstone: High-Performance Concurrent Microservice Engine
Course Certificate0%

Complete all lessons to earn

LearnImplicit Interfaces & Duck Typing with Typesafety
10 / 20 0%
Lesson 10 of 20
15 mins read

Implicit Interfaces & Duck Typing with Typesafety

PreviousNext Lesson
In Plain English

In Go, interfaces are satisfied implicitly without "implements" keywords. If a type provides the methods declared in an interface, it automatically implements it. Learn interface dispatch, empty interface any, and type assertions.

The Mental Model

"Think of an interface like a USB-C port definition. Any device maker can build a charger or hard drive that fits USB-C without signing a contract with laptop vendors—as long as the physical pins match."

Deep Dive: How It Works

Implicit Implementation: Types satisfy interfaces automatically by declaring matching method signatures.

Decoupled Design: Consumers define the minimal interface they require (e.g. io.Reader with Read(p []byte)).

The any Type: any (alias for interface{}) represents zero methods and can hold any value.

Syntax Blueprint

type Greeter interface { Greet() string }
func Welcome(g Greeter) { fmt.Println(g.Greet()) }

Define interface signatures and accept interface parameters in functions for polymorphic dispatch.

PointCore Rules to Remember

Point star
Zero Ceremony: No "implements" keyword needed; interfaces are satisfied automatically.
Point star
Small Interfaces: The standard library favors single-method interfaces like io.Reader and fmt.Stringer.
Point star
Type Assertions: Use val, ok := i.(ConcreteType) to safely inspect underlying types.

Common Beginner Traps & How to Fix Them

Mistake:Checking if an interface variable is nil when it holds a nil pointer of a concrete type.

Why it happens: An interface is only nil if both its type descriptor and underlying value are nil.

How to fix: Return a nil interface directly rather than a typed nil pointer.

Pro Tip: Follow the Go maxim: "Accept interfaces, return structs". Functions should accept the smallest interface required and return concrete types.

Live Interactive Example

Hit Run Code to see it live
Polymorphic Payment Processors
Go 1.22 / Runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Output Console
Click "Run Code" to view the rendered output.
How it works: Both CreditCard and CryptoWallet satisfy PaymentGateway implicitly without explicit inheritance.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Implement a Stringer Formatter

  • PointCreate a Product struct with Title string and Price int.
  • PointImplement the fmt.Stringer interface method String() string returning "Product: [Title] ($[Price])".
  • PointIn main(), create a Product and print it using fmt.Println.
1
2
3
4
5
6
7
8
9
10
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates