Build robust Go programs through idiomatic error handling: error interface, Sentinel Errors, wrapping with %w, Custom Error Types, panic/recover, and HTTP mapping.
Millions of lines of C++ and Java run in production. Go is the most common way to modernize such systems: fast builds, one binary, built-in concurrency. But literal porting — line by line — preserves the architecture of the old code including its design flaws (the same phenomenon the C→Rust research proved as the "Fallacy"). You get faster, simpler code — but no guarantee that it is better.
The honest decision question for every module:
Is 1:1 behaviour required (protocols, file formats)?
yes → port + round-trip tests against the original
no → rewrite and treat the old API as the contract
Ship of Theseus instead of big bang
Port one component at a time while the system keeps running. Every component gets its own boundary (interface/HTTP/CLI) and its own round-trip test. Only when the Go version provably produces the same results do you switch off the original. No giant rewrite, no months-long phase without a shippable state.
// The boundary every substituted module needs:
type OpStore interface {
Load(id string) ([]Op, error)
Save(id string, ops []Op) error
}
// The Go module implements the interface; everything else only talks to
// the interface. The C++/Java side can be switched off at any time.
Check: When should you port a legacy component instead of rewriting it?
Answer: When the behaviour is stable and complex and must be preserved 1:1 (protocols, formats)
Behaviour that must stay exact (file formats, protocols) is ported with round-trip tests. Behaviour that should change is rewritten.
The fastest path through any port — the table you always come back to:
| C++ / Java | Go | Meaning |
|---|---|---|
| class + private fields | struct + unexported fields (lowercase) | no class concept |
| inheritance + virtual methods | interfaces + struct composition | behaviour via contracts |
| constructor / destructor | constructor func NewXxx() + defer | cleanup in place |
| exceptions / try-catch | error return values + if err != nil | errors are data |
| RAII (lock in scope) | defer lock.Unlock() | guaranteed at scope end |
std::vector<T> / ArrayList | []T (slice) | dynamic array |
std::map / HashMap | map[K]V | associative storage |
| smart pointers / GC concerns | built-in GC | never think about delete |
| templates / generics | type parameters [T any] | since Go 1.18 |
| threads + mutex | goroutines + channels (sync.Mutex) | concurrency in the language |
| promise/future | channels | async as data flow |
std::stringstream | strings.Builder / bytes.Buffer | efficient appending |
| enum classes | type Kind int + iota | typed constants |
| getters/setters | direct field access | only add complexity if needed |
// Typed constants instead of enum class:
type Status int
const (
StatusOpen Status = iota // 0
StatusDone // 1
StatusClosed // 2
)
Interfaces instead of inheritance
Inheritance hierarchies become interfaces: small, open, implementable
by different types. A type satisfies an interface automatically through its
methods — no implements, no extends.
// Java: interface Writer { void write(String s); }
// Go:
type Writer interface {
Write(s string) error
}
// Any type with Write(string) error is a Writer. Done.
Check: What replaces C++ RAII discipline (a lock released at scope end) most directly in Go?
Answer: defer lock.Unlock() right after the lock
defer runs the Unlock at the end of the function — even on early return. Go needs no destructors and no RAII classes for that.
The biggest cultural shift when porting: exceptions disappear. Errors are values that every function returns explicitly. That sounds like boilerplate and is actually focus: you can see at every call site where something can go wrong.
// Java: throw new IOException(...) somewhere deep, catch on top.
// Go:
func readConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err // the caller decides
}
cfg, err := parse(data)
if err != nil {
return nil, fmt.Errorf("config %s: %w", path, err)
}
return cfg, nil
}
Chaining errors: %w & errors.Is
fmt.Errorf("...: %w", err) wraps the original error without destroying it.
With errors.Is / errors.As you can check deep in the chain whether a
specific error occurred — Go's answer to "which exception is this?".
import "errors"
var ErrNotFound = errors.New("not found")
// Somewhere deep in the chain:
if !exists {
return ErrNotFound
}
// At the top:
if errors.Is(err, ErrNotFound) {
fmt.Println("File or record missing")
// → File or record missing
}
⚠ Common mistake:
fmt.Errorf("config %s: %v", path, err)merely pastes the original error into the message as text — the chain is destroyed, anderrors.Is(err, ErrNotFound)will never betrueagain. Only the verb%wkeeps the error visible toerrors.Isanderrors.As.
panic/recover exists in Go — but for programmer errors and broken
invariants, not for expected failures (inputs, files, network). Porting rule
of thumb: every throw becomes a return …error; only worst-case decisions
(nil deref, broken invariant) may panic.
// NOT like this — expected errors belong in return values:
func parseAge(s string) int {
n, err := strconv.Atoi(s)
if err != nil {
panic(err) // ✗ not an exception replacement!
}
return n
}
Check: What is the idiomatic Go replacement for an exception with try/catch?
Answer: A function returns (value, error); the caller checks err
Errors as return values are the Go idiom. panic is reserved for programmer errors, not for expected failures.
C++/Java concurrency usually means: threads, locks, thread pools, futures. In Go the unit is the goroutine — lightweight (a few KB), create millions of them, and communication runs over channels instead of shared state.
// Java: ExecutorService + Callable + Future.get()
// Go: goroutine + channel
func main() {
type Result struct {
name string
err error
}
results := make(chan Result)
for _, file := range files {
file := file // bind the loop variable locally
go func() {
out, err := process(file)
results <- Result{name: file, err: err}
}()
}
for range files {
r := <-results
if r.err != nil {
fmt.Println("Error:", r.name)
// → Error: config.yaml
}
}
}
Don't communicate by sharing memory; share memory by communicating
The Go mantra: instead of protecting a struct with a lock ("share and protect"), you send the data through a channel — exactly one owner is responsible. Channels couple concurrent parts in a data-flow way, just like streams in reactive systems.
// Deliver values over a channel (stream replacement):
out := make(chan int)
go func() {
defer close(out)
for i := 0; i < 5; i++ {
out <- i * i
}
}()
for v := range out {
fmt.Println(v) // 0 1 4 9 16 — close terminates the range loop
}
⚠ Common mistake: If the receive loop above returns early on the first error, the remaining goroutines block forever on sending over the unbuffered channel — a goroutine leak. Either collect all results, buffer the channel (
make(chan Result, len(files))), or signal cancellation through acontext.Context.
go test -race compiles your program with instrumentation and reports every
data race at runtime. When porting lock-based code to channel-based code,
this is the most important check of all.
go test -race ./...
# WARNING: DATA RACE → line, both accesses, stack traces
// Classic porting mistake — shared variable without protection:
total := 0
for i := 0; i < 100; i++ {
go func() { total++ }() // ✗ data race!
}
// correct: atomic counters (sync/atomic) or a channel
Check: How do goroutines communicate idiomatically?
Answer: Over channels — data flows from one sender to one receiver
Channels transport data and couple concurrent parts; range over a closed channel terminates the loop cleanly.
"It compiles and runs" is not proof. For every ported unit you need:
error, not a panic.go test -race ./... — no data races in ported concurrency.// Fuzz tests: random inputs into the port — finds translation edge cases.
func FuzzParses(f *testing.F) {
f.Add("hello")
f.Add("42")
f.Fuzz(func(t *testing.T, s string) {
// The parser must NEVER panic — for any input.
_ = parse(s)
})
}
The five-point checklist after every port
| Check | Command/tool | Fails on |
|---|---|---|
| Format | gofmt, go vet ./... | unclean style, suspicious spots |
| Behaviour | go test ./... | round-trip/error deviation |
| Races | go test -race ./... | simultaneous writes |
| Edge cases | go test -fuzz=. | panics on random data |
| Performance | go test -bench=. | regression in the port |
Check: How do you prove that a ported module behaves like the original?
Answer: Round-trip tests with the same inputs on both sides + error-path tests
Round-trip + error paths compare behaviour explicitly with the original. Compiler success is only half the story.
Takeaways:
%w chaining + errors.Is instead of try/catchgo test -raceCourse navigation: ← Module 2 · All 20 modules · Module 4 →