Go by Contrast
Errors are values
Lesson 2 of 5
What you'll learn
- Understand Go's error-as-value model
- Contrast it with JS/TS try/catch and thrown exceptions
- See why the explicit
if err != nilpattern is everywhere in Go
In Go there is no exception control flow for ordinary failures. A function that can fail returns two values: the result and an error. The caller checks the error before trusting the result.
val, err := strconv.Atoi("42")
if err != nil {
return 0, err
}
fmt.Println(val) // 42
In TypeScript, the same operation throws, and you opt into handling it with try/catch:
function atoi(s: string): number {
const n = Number(s);
if (Number.isNaN(n)) throw new Error("invalid number: " + s);
return n;
}
try {
const val = atoi("42");
} catch (e) {
// handle it — but the type system never forced you to
}
The error is part of the signature
The crucial difference: in Go the failure mode is written into the return type, so it's visible at the call site. You'll see this rhythm constantly:
data, err := os.ReadFile("config.yaml")
if err != nil {
return fmt.Errorf("reading config: %w", err)
}
fmt.Errorf with %w wraps the error, adding context while preserving the original — the rough equivalent of new Error(msg, { cause }) in modern JS. An error is just any value implementing an Error() string method, so errors are ordinary data you can inspect, compare, and pass around.
Check, don't catch
Go pushes error handling to the call site. It's more verbose than try/catch, but a failure can't silently propagate past a function that ignored it — the err is right there in the return, waiting to be checked.
The challenge is a JS model of Go's (value, error) return — plain JavaScript returning a tuple and checking it at the call site.
Run it. This models Go's (result, error) return and the if err != nil check in plain JS.
How does a Go function that can fail typically signal that failure to its caller?
Next: how Go decides whether a type "fits" an interface — without ever saying implements.
Saved on this device. Sign in to sync your progress everywhere.