These are the notes for Go episode 72. Priya joins Raju's team. Her first task is a bug in dosa stock, and she can't find it: the code is split into models/, services/, utils/ and helpers/, and full of names like OrderServiceManagerImpl.GetOrderData(). The code works, but it doesn't read like Go. Today we learn idiomatic Go: the way experienced Go programmers write it, so that any Go developer feels at home on day one, and the architecture that keeps a growing service easy to change.
All outputs below are from real runs (Go 1.24.7, linux/amd64), through the same runner the video's compiler uses. Error streams (compiler errors, panics) are printed after the normal output.
Facts and sources
- The Go proverbs (go-proverbs.github.io, read from its GitHub repository for this episode) are "the basis of a talk by Rob Pike" at Gopherfest SV 2015. The list includes: "Don't communicate by sharing memory, share memory by communicating." "Concurrency is not parallelism." "Channels orchestrate; mutexes serialize." "The bigger the interface, the weaker the abstraction." "Make the zero value useful." "interface{} says nothing." "Gofmt's style is no one's favorite, yet gofmt is everyone's favorite." "A little copying is better than a little dependency." "Syscall must always be guarded with build tags." "Cgo must always be guarded with build tags." "Cgo is not Go." "With the unsafe package there are no guarantees." "Clear is better than clever." "Reflection is never clear." "Errors are values." "Don't just check errors, handle them gracefully." "Design the architecture, name the components, document the details." "Documentation is for users." "Don't panic."
- Effective Go, "Names": "the convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names"; "By convention, packages are given lower case, single-word names; there should be no need for underscores or mixedCaps"; bufio's buffered reader "is called Reader, not BufReader"; the getter for a field
owner"should be called Owner (upper case, exported), not GetOwner"; "one-method interfaces are named by the method name plus an -er suffix or similar modification to construct an agent noun". - Go Code Review Comments (go.dev/wiki/CodeReviewComments): receiver names: "often a one or two letter abbreviation of its type suffices", "Don't use generic names such as "me", "this" or "self"", and if you call the receiver
cin one method, don't call itclin another; package names: "Avoid meaningless package names like util, common, misc, api, types, and interfaces", and no stutter: "you don't need type ChubbyFile, which clients will write as chubby.ChubbyFile"; initialisms: "URL" should appear as "URL" or "url", never "Url", and "appID" instead of "appId"; mixed caps: an unexported constant ismaxLengthnotMaxLengthorMAX_LENGTH; interfaces "generally belong in the package that uses values of the interface type", and "Do not define interfaces before they are used".
The problem: code nobody can find
Priya's view of the shop:
shop/
models/ order.go stock.go user.go
services/ order_service_manager_impl.go stock_service.go
handlers/ order_handler.go
utils/ helpers.go common.go
orders := services.NewOrderServiceManagerImpl()
data := orders.GetOrderData(id)
Two separate problems: the names were copied from other languages' habits, and the packages are split by kind of code rather than by what the code does. Fixing a dosa stock bug means opening four folders.
Idiomatic code follows the natural style of its language. Idiomatic Go is simple, explicit, and looks the same in every project, because the whole community follows the same small set of conventions (and gofmt formats everyone's code the same way).
The Go proverbs
A proverb is a short saying that carries a piece of wisdom ("slow and steady wins the race"). Rob Pike, one of Go's three creators (episode 1), collected Go proverbs in a 2015 talk. The ones that guide design most:
| Proverb | What it means in practice |
|---|---|
| Clear is better than clever. | Code is read far more often than written. Prefer the obvious loop to the clever trick. |
| The bigger the interface, the weaker the abstraction. | One- or two-method interfaces (io.Reader) are easy to implement, combine and fake. A 20-method interface fits one type only. |
| Make the zero value useful. | var b bytes.Buffer just works. Design your types the same way. |
| A little copying is better than a little dependency. | Copying three lines can be cheaper than importing a library (and its updates, bugs and licence). |
| Errors are values. / Don't just check errors, handle them gracefully. | Errors are ordinary results: wrap them with context, map them, decide; don't just pass them up blindly (episodes 24–25). |
| Don't panic. | Return errors; keep panic for real programmer bugs (episode 26). |
| Design the architecture, name the components, document the details. | Good names carry the design; docs explain the rest. |
Naming the Go way
Names in Go are read together with their package. A shoe shop's sign says "Shoes", not "Shoe Shop Shoes"; at home, Rajesh is just "Raju", every time; and you ask someone their "name?", not their "get name?".
| Rule | Idiomatic | Not idiomatic |
|---|---|---|
| MixedCaps, no underscores | maxLength, OrderID |
max_length, MAX_LENGTH |
| Capital first letter = exported | Total (other packages can use it), priceOf (only this package) |
— |
| Package names: lower case, one word, meaningful | orders, stock, httpapi |
utils, common, misc, orderUtils, order_service |
| No stutter (the package name repeated in the type) | orders.Service, bufio.Reader |
orders.OrderService, bufio.BufReader |
| Short, consistent receivers | func (o *Order) Total() |
func (this *Order), self, me; o in one method and ord in another |
Getters without Get |
o.Owner(), setter o.SetOwner(x) |
o.GetOwner() |
| Initialisms keep one case | URL, userID, ServeHTTP, appID |
Url, userId, ServeHttp, appId |
| One-method interfaces end in -er | Reader, Writer, Notifier, Stringer |
IReader, ReaderInterface |
| Name length follows scope | i, r, w in a short function; defaultCutoffHour at package level |
theIndexOfTheCurrentOrder in a 3-line loop |
Exported means visible to other packages; the compiler enforces it by the first letter alone.
The episode's program (NAMES)
main.go:
package main
import (
"fmt"
"shop/orders"
)
func main() {
o := orders.Order{ID: "A1", Qty: 2}
fmt.Println(orders.Total(o))
fmt.Println(orders.priceOf("dal")) // lower case = unexported
}
orders/orders.go:
package orders
type Order struct {
ID string
Qty int
}
func Total(o Order) int { return o.Qty * priceOf("dal") } // exported: capital T
func priceOf(item string) int { return 60 } // unexported: only inside package orders
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go build ./...
Output:
$ go build ./...
# shop
./main.go:12:24: name priceOf not exported by package orders
name priceOf not exported by package orders: the small p keeps priceOf private to orders. That's a feature, not a bug: the exported names are the package's API, the promises other code may depend on. Keep that list small, so you're free to change everything else.
Useful zero values
Every Go variable starts at its zero value (episode 3): 0, "", false, nil, or a struct of zero fields. A type has a useful zero value when it works right away, without a constructor. A new notebook works the moment you open it; a pressure cooker without its gasket fitted fails as soon as you use it.
The standard library is full of useful zero values: bytes.Buffer, strings.Builder, sync.Mutex, sync.WaitGroup, sync.Once.
The episode's program (ZERO)
main.go:
package main
import (
"bytes"
"fmt"
"sync"
)
// Tally counts orders per dish
type Tally struct {
mu sync.Mutex // zero value: an unlocked mutex, ready
counts map[string]int // zero value: nil map
}
func (t *Tally) Add(dish string) {
t.mu.Lock()
defer t.mu.Unlock()
t.counts[dish]++
}
func main() {
var buf bytes.Buffer // zero value: an empty buffer, ready
buf.WriteString("orders: ")
fmt.Println(buf.String())
var t Tally // no constructor called
t.Add("dosa")
fmt.Println(t.counts)
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go run .
Output:
$ go run .
orders:
panic: assignment to entry in nil map
goroutine 1 [running]:
main.(*Tally).Add(0x4db4f8?, {0x4b504f?, 0xc000104f28?})
main.go:18 +0x9a
main.main()
main.go:27 +0xd0
exit status 2
The buffer worked; Tally didn't. Its zero value holds a nil map, and writing to a nil map panics (episode 15). The mutex inside was fine.
The fix (ZERO2): lazy initialisation
Lazy initialisation = creating something the first time it's needed, instead of in a constructor.
main.go:
package main
import (
"bytes"
"fmt"
"sync"
)
// Tally counts orders per dish
type Tally struct {
mu sync.Mutex // zero value: an unlocked mutex, ready
counts map[string]int // zero value: nil map
}
func (t *Tally) Add(dish string) {
t.mu.Lock()
defer t.mu.Unlock()
if t.counts == nil { // make the zero value useful
t.counts = map[string]int{}
}
t.counts[dish]++
}
func main() {
var buf bytes.Buffer // zero value: an empty buffer, ready
buf.WriteString("orders: ")
fmt.Println(buf.String())
var t Tally // no constructor called
t.Add("dosa")
t.Add("dosa")
t.Add("idli")
fmt.Println(t.counts)
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go run .
Output:
$ go run .
orders:
map[dosa:2 idli:1]
Now var t Tally (or a Tally field inside another struct) just works, and nobody has to remember to call NewTally(). Note that the nil check happens while holding the lock, so two goroutines can't both create the map.
When a constructor is needed (required dependencies, validation), provide NewX and document that the zero value is not usable. http.Client{} and http.Server{} are useful zero values with sensible defaults; *sql.DB must come from sql.Open.
Small interfaces
"The bigger the interface, the weaker the abstraction." Compare:
// small: anything that can be read from — files, network connections, strings, gzip streams
type Reader interface {
Read(p []byte) (n int, err error)
}
// big: only one type in the world will ever implement this
type OrderManager interface {
Create(...) error; Update(...) error; Delete(...) error; List(...) ([]Order, error)
Export(...) error; Import(...) error; Notify(...) error; Audit(...) error
}
- A small interface is easy to implement, easy to fake in tests (episode 71), and easy to combine (
io.ReadWriterembedsReaderandWriter, episode 22). - Define it where it's used, with only the methods that package calls.
- "Accept interfaces, return structs" (episode 22): functions take the small interface they need and return concrete types, so callers get the full type and are free to define their own interfaces.
Domain types
Salt and sugar look the same: one wrong spoon and the kheer is ruined. An amount in paise and an amount in rupees are both just int. A domain type is a type named after a real idea from the business (Paise, Rupees, AccountID, DishID), built on a basic type with type Paise int64 (a defined type, episode 19). The meaning becomes part of the type, so the compiler checks it.
The bug (DOM1)
main.go:
package main
import "fmt"
var balance = map[string]int{"raju": 50000, "priya": 20000} // in paise
// Transfer moves money. amount is in paise (100 paise = 1 rupee)
func Transfer(from, to string, amount int) {
balance[from] -= amount
balance[to] += amount
}
func main() {
Transfer("raju", "priya", 150) // Raju pays Priya Rs 150 ... or does he?
fmt.Println(balance)
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go run .
Output:
$ go run .
map[priya:20150 raju:49850]
Priya went from 20000 to 20150 paise: she got Rs 1.50, not Rs 150. No error, no warning.
With domain types (DOM2)
main.go:
package main
import "fmt"
// domain types: they carry the meaning, the compiler checks it
type AccountID string
type Paise int64
type Rupees int64
func (r Rupees) Paise() Paise { return Paise(r * 100) }
func (p Paise) String() string { return fmt.Sprintf("Rs %d.%02d", p/100, p%100) }
var balance = map[AccountID]Paise{"raju": 50000, "priya": 20000}
func Transfer(from, to AccountID, amount Paise) {
balance[from] -= amount
balance[to] += amount
}
func main() {
Transfer("raju", "priya", Rupees(150))
fmt.Println(balance)
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go run .
Output:
$ go run .
# shop
./main.go:21:31: cannot use Rupees(150) (constant 150 of int64 type Rupees) as Paise value in argument to Transfer
cannot use Rupees(150) (constant 150 of int64 type Rupees) as Paise value in argument to Transfer: the bug can't even be built. Go never converts between two defined types implicitly (episode 4), even when both are int64 underneath.
The fix (DOM3): convert explicitly
Only the call changes, to Transfer("raju", "priya", Rupees(150).Paise()).
$ go run .
map[priya:Rs 350.00 raju:Rs 350.00]
Notes:
- The untyped string constants
"raju"and"priya"are accepted asAccountIDbecause untyped constants take the type they're used as (episode 5). Astringvariable would needAccountID(s). Paisehas aString()method, sofmtprintsRs 350.00(thefmt.Stringerinterface, episode 21).- Store money as an integer number of the smallest unit (paise), never as
float64:0.1 + 0.2is not exactly0.3in floating point. - Domain types don't catch every mix-up:
Transfer(priya, raju, amount)with both argumentsAccountIDstill compiles. For several values of the same type, a struct with named fields (TransferRequest{From: ..., To: ..., Amount: ...}) makes the call read unambiguously.
Package by layer vs package by feature
A supermarket with one aisle for "everything in a box" and another for "everything in a bottle" makes you walk the whole shop for one dish. Real shops arrange aisles by purpose: dairy, snacks, spices.
| Package by layer | Package by feature | |
|---|---|---|
| Groups code by | what kind of code it is | what it does for the business |
| Folders | models/, services/, handlers/, utils/ |
orders/, stock/, users/, httpapi/, cmd/shop/ |
| One change touches | every folder | one folder (usually) |
| Package names | say nothing about the domain | say what's inside |
| Import cycles | common (every layer needs the others) | rare |
The import cycle (CYCLE)
main.go:
package main
import (
"fmt"
"shop/services"
)
func main() { fmt.Println(services.Checkout("A1")) }
models/order.go:
package models
import "shop/services"
type Order struct{ ID, Dish string }
// an order wants to know its price...
func (o Order) Price() int { return services.PriceOf(o.Dish) }
services/orders.go:
package services
import "shop/models"
func PriceOf(dish string) int { return 60 }
// ...and the service needs the order type
func Checkout(id string) int { return models.Order{ID: id, Dish: "dosa"}.Price() }
utils/utils.go:
package utils // everything that has no home ends up here
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go build ./...
Output:
$ go build ./...
package shop
imports shop/services from main.go
imports shop/models from orders.go
imports shop/services from order.go: import cycle not allowed
Go forbids import cycles (packages that import each other directly or through others), and prints the whole loop. With packages by layer this keeps happening: models want behaviour from services, services need the models' types. Package by feature keeps a type and the code that works on it together, so the dependencies point one way. (The empty utils package shows where code without a home ends up.)
Common Go layout (episode 29): cmd/<app>/main.go for each binary, feature packages at the top level or under internal/ (so other modules can't import them), and no pkg/ unless you have a reason.
Hexagonal architecture: ports and adapters
A laptop does the real work and doesn't care what's plugged into it. It has ports with standard shapes (USB-C), and you plug adapters into them (a charger, a monitor, a pen drive) and swap them freely.
- Core (the domain): your business rules, with no HTTP, no SQL, no frameworks inside.
- Port: an interface the core owns that says what it needs from the outside (
StockwithTake). Ports that the outside calls into the core are just the core's exported methods (Service.Place). - Adapter: code that connects the core to one real technology: an in-memory store, a Postgres store, an HTTP handler, a gRPC server, a CLI.
- Hexagonal architecture (also called ports and adapters) draws the core in the middle and the adapters around it; the hexagon shape just leaves room for many sides. Clean architecture is a close cousin with the same key rule: dependencies point inward, towards the core. The core never imports an adapter.
The episode's program (HEX)
main.go:
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"shop/httpapi"
"shop/memory"
"shop/orders"
)
func main() {
db := memory.NewStore(map[string]int{"dosa": 2}) // adapter: storage
svc := orders.NewService(db) // core: business rules
srv := httptest.NewServer(httpapi.New(svc)) // adapter: HTTP
defer srv.Close()
for i, qty := range []string{"1", "5", "1"} {
if i == 2 {
db.Down = true // the database goes away
}
resp, _ := http.Post(srv.URL+"/orders?dish=dosa&qty="+qty, "", nil)
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("qty %s -> %d %s", qty, resp.StatusCode, body)
}
}
orders/orders.go:
package orders // the core: no HTTP, no SQL, just the rules
import "errors"
var ErrOutOfStock = errors.New("out of stock")
// Stock is a port: what the core needs from storage
type Stock interface {
Take(dish string, qty int) (left int, err error)
}
type Service struct{ stock Stock }
func NewService(s Stock) *Service { return &Service{stock: s} }
func (s *Service) Place(dish string, qty int) (int, error) {
if qty < 1 {
return 0, errors.New("qty must be at least 1")
}
return s.stock.Take(dish, qty)
}
memory/store.go:
package memory // an adapter: one way to store stock
import (
"fmt"
"shop/orders"
)
type Store struct {
left map[string]int
Down bool
}
func NewStore(m map[string]int) *Store { return &Store{left: m} }
func (s *Store) Take(dish string, qty int) (int, error) {
if s.Down {
return 0, fmt.Errorf("memory: dial db.prod:5432 as user shop: connection refused")
}
if s.left[dish] < qty {
return s.left[dish], orders.ErrOutOfStock
}
s.left[dish] -= qty
return s.left[dish], nil
}
httpapi/handler.go:
package httpapi // an adapter: turns HTTP into calls on the core
import (
"errors"
"fmt"
"net/http"
"strconv"
"shop/orders"
)
func New(svc *orders.Service) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
qty, _ := strconv.Atoi(r.URL.Query().Get("qty"))
left, err := svc.Place(r.URL.Query().Get("dish"), qty)
switch {
case errors.Is(err, orders.ErrOutOfStock): // the boundary maps errors
http.Error(w, fmt.Sprintf("only %d left", left), http.StatusConflict)
case err != nil:
fmt.Println(" log (team only):", err) // details stay inside
http.Error(w, "internal error", http.StatusInternalServerError)
default:
fmt.Fprintf(w, "placed, %d left\n", left)
}
})
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go run .
Output:
$ go run .
qty 1 -> 200 placed, 1 left
qty 5 -> 409 only 1 left
log (team only): memory: dial db.prod:5432 as user shop: connection refused
qty 1 -> 500 internal error
- Quantity 1:
200 placed, 1 left. Quantity 5: the core returnedorders.ErrOutOfStock, and the HTTP adapter translated it into409 only 1 left. - When the "database" is down, the customer sees only
500 internal error. The details (the hostdb.prod:5432and the user nameshop) appear only in the team's log line. - The imports show the direction:
httpapiandmemoryimportorders;ordersimports neither.mainimports all three and wires them (the composition root, episode 71).
Errors at boundaries
Like a waiter who says "sorry, dosa is over for today", and not that the gas cylinder leaked in the kitchen:
- The core returns domain errors that mean something to the business:
orders.ErrOutOfStock,orders.ErrUnknownDish. Useerrors.Is/errors.As(episode 25) to recognise them through any wrapping. - Each adapter translates them for its world: HTTP →
409 Conflict/404 Not Found; gRPC →codes.FailedPrecondition/codes.NotFound(episode 69); a CLI → a message and an exit code. - Never send raw internal errors to users. They leak host names, user names, file paths and SQL, which helps attackers (episode 66) and confuses customers.
- Unknown errors become a generic
500 internal error; log the details once, at the boundary (episode 25). - Because the core never imports
net/http, you can test the rules with plain Go tests, no server needed.
Avoiding over-abstraction
Five floors of parking for one scooter:
type IOrderService interface { Place(DishID, int) (Paise, error) }
type OrderServiceImpl struct{ repo IOrderRepository }
type OrderServiceFactory struct{}
func (OrderServiceFactory) Create() IOrderService { ... }
// one implementation, four types, three files
Just enough:
type Service struct{ stock Stock }
func NewService(s Stock) *Service { return &Service{stock: s} }
- Add an interface when there is a second implementation or a test needs a fake, not before.
- No
Iprefixes and noImplsuffixes: the concrete type gets the good name. - Don't wrap the standard library in your own "framework" layer.
net/http,database/sqlandlog/slogare already the abstraction. - "A little copying is better than a little dependency": a small helper copied into two packages can be better than a shared
utilspackage that everything depends on.
API stability
If the shape of power sockets changed, every plug in the country would break. A public API (the exported names other code depends on) is that socket.
Breaking change (API)
main.go:
package main
import (
"fmt"
"shop/payments"
)
// Raju's app implements the library's interface with its own type
type upiGateway struct{}
func (upiGateway) Charge(paise int64) error { return nil }
func main() {
var g payments.Gateway = upiGateway{}
fmt.Println(payments.Pay(g, 15000))
}
payments/payments.go:
package payments // a library many teams import, version 1.4
// v1.5 "just adds one method" to an exported interface
type Gateway interface {
Charge(paise int64) error
Refund(paise int64) error
}
func Pay(g Gateway, paise int64) error { return g.Charge(paise) }
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go build ./...
Output:
$ go build ./...
# shop
./main.go:15:30: cannot use upiGateway{} (value of struct type upiGateway) as payments.Gateway value in variable declaration: upiGateway does not implement payments.Gateway (missing method Refund)
Raju changed nothing, and his build broke the day he upgraded the library: adding a method to an exported interface breaks every type outside the package that implements it.
The compatible way (API2): a new, optional interface
main.go:
package main
import (
"fmt"
"shop/payments"
)
type upiGateway struct{} // unchanged: still compiles
func (upiGateway) Charge(paise int64) error { return nil }
func main() {
var g payments.Gateway = upiGateway{}
fmt.Println("pay:", payments.Pay(g, 15000))
fmt.Println("refund:", payments.Refund(g, 15000))
}
payments/payments.go:
package payments // v1.5, the compatible way
import "errors"
type Gateway interface {
Charge(paise int64) error
}
// new behaviour goes in a NEW, optional interface
type Refunder interface {
Refund(paise int64) error
}
var ErrNoRefunds = errors.New("this gateway does not support refunds")
func Pay(g Gateway, paise int64) error { return g.Charge(paise) }
func Refund(g Gateway, paise int64) error {
if r, ok := g.(Refunder); ok { // does this gateway also refund?
return r.Refund(paise)
}
return ErrNoRefunds
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go run .
Output:
$ go run .
pay: <nil>
refund: this gateway does not support refunds
The standard library does exactly this: io.WriterTo and io.ReaderFrom are optional interfaces that io.Copy checks for with a type assertion, and http.Flusher is an optional interface a ResponseWriter may implement.
| Change | Safe? |
|---|---|
| add a new function, type, method on a struct, or constant | safe |
| add a field to a struct | safe (callers using keyed literals; unkeyed T{a, b} literals break) |
| add a new, optional interface | safe |
| remove or rename anything exported | breaking |
| change a function's parameters or results | breaking |
| add a method to an exported interface | breaking for implementers |
If you must break, semantic versioning (episode 28) says bump the major version, and Go modules put the major version in the import path: example.com/payments/v2. Go itself keeps the Go 1 compatibility promise (episode 2).
Idiomatic Go in one page
httpapi (adapter) grpcapi (adapter)
\ /
▼ ▼
orders: core rules + ports (Stock)
▲ ▲
/ \
memory (adapter) postgres (adapter)
- Names: MixedCaps, short consistent receivers, lower-case one-word packages, no stutter, no
utils,URL/ID,Owner()notGetOwner(),-erinterfaces. - Types: useful zero values, small interfaces defined where used, domain types for meaning (money in integer paise).
- Packages by feature; the core imports no HTTP/SQL; dependencies point inward; no import cycles.
- Errors: domain errors in the core, translated at the edge, details only in logs.
- Just enough abstraction; export less; add, don't change.
Mini project: refactor the shop
- Move
models/,services/andutils/into feature packages:orders/,memory/,httpapi/. - Rename to Go style:
OrderServiceManagerImpl→orders.Service,GetOrderData→ a method that says what it returns. - Add
PaiseandDishIDtypes, and aCartwhose zero value works. - A
Stockport with an in-memory adapter (and, for extra credit, an SQLite adapter usingdatabase/sqlfrom episodes 67–68), plus a contract test: one test everyStockadapter must pass. - Map
ErrOutOfStock→ 409,ErrUnknownDish→ 404, bad input → 400, anything else → 500 plus a log line.
Solution
main.go:
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"shop/httpapi"
"shop/memory"
"shop/orders"
)
func main() {
stock := memory.NewStock(map[orders.DishID]int{"dosa": 3})
menu := map[orders.DishID]orders.Paise{"dosa": 6000}
srv := httptest.NewServer(httpapi.New(orders.NewService(stock, menu)))
defer srv.Close()
for _, q := range []string{"dish=dosa&qty=2", "dish=dosa&qty=2", "dish=idli&qty=1"} {
resp, _ := http.Post(srv.URL+"/orders?"+q, "", nil)
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%-16s -> %d %s", q, resp.StatusCode, b)
}
}
orders/money.go:
package orders
import "fmt"
type Paise int64
type DishID string
func (p Paise) String() string { return fmt.Sprintf("Rs %d.%02d", p/100, p%100) }
// Cart's zero value is an empty, usable cart
type Cart struct {
items map[DishID]int
}
func (c *Cart) Add(d DishID, qty int) {
if c.items == nil {
c.items = map[DishID]int{}
}
c.items[d] += qty
}
func (c *Cart) Total(menu map[DishID]Paise) Paise {
var t Paise
for d, q := range c.items {
t += menu[d] * Paise(q)
}
return t
}
orders/service.go:
package orders
import "errors"
var (
ErrOutOfStock = errors.New("out of stock")
ErrUnknownDish = errors.New("unknown dish")
)
// Stock is the port the core needs from storage
type Stock interface {
Take(d DishID, qty int) (left int, err error)
}
type Service struct {
stock Stock
menu map[DishID]Paise
}
func NewService(s Stock, menu map[DishID]Paise) *Service { return &Service{stock: s, menu: menu} }
func (s *Service) Place(d DishID, qty int) (Paise, error) {
price, ok := s.menu[d]
if !ok {
return 0, ErrUnknownDish
}
if _, err := s.stock.Take(d, qty); err != nil {
return 0, err
}
var c Cart
c.Add(d, qty)
return c.Total(map[DishID]Paise{d: price}), nil
}
orders/orders_test.go:
package orders
import "testing"
func TestCartZeroValue(t *testing.T) {
var c Cart // no constructor
c.Add("dosa", 2)
c.Add("idli", 1)
got := c.Total(map[DishID]Paise{"dosa": 6000, "idli": 4000})
if got != 16000 {
t.Fatalf("got %v", got)
}
t.Log("total:", got)
}
memory/stock.go:
package memory
import (
"sync"
"shop/orders"
)
type Stock struct {
mu sync.Mutex
left map[orders.DishID]int
}
func NewStock(m map[orders.DishID]int) *Stock { return &Stock{left: m} }
func (s *Stock) Take(d orders.DishID, qty int) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.left[d] < qty {
return s.left[d], orders.ErrOutOfStock
}
s.left[d] -= qty
return s.left[d], nil
}
memory/stock_test.go:
package memory
import (
"errors"
"testing"
"shop/orders"
)
// a contract test: any Stock adapter (memory, SQLite, Postgres) must pass it
func TestStockContract(t *testing.T) {
var s orders.Stock = NewStock(map[orders.DishID]int{"dosa": 2})
if left, err := s.Take("dosa", 2); err != nil || left != 0 {
t.Fatalf("take 2: left=%d err=%v", left, err)
}
if _, err := s.Take("dosa", 1); !errors.Is(err, orders.ErrOutOfStock) {
t.Fatalf("want ErrOutOfStock, got %v", err)
}
}
httpapi/handler.go:
package httpapi
import (
"errors"
"fmt"
"net/http"
"strconv"
"shop/orders"
)
func New(svc *orders.Service) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
qty, err := strconv.Atoi(r.URL.Query().Get("qty"))
if err != nil || qty < 1 {
http.Error(w, "qty must be a positive number", http.StatusBadRequest)
return
}
total, err := svc.Place(orders.DishID(r.URL.Query().Get("dish")), qty)
switch {
case errors.Is(err, orders.ErrOutOfStock):
http.Error(w, "sorry, not enough left", http.StatusConflict)
case errors.Is(err, orders.ErrUnknownDish):
http.Error(w, "no such dish", http.StatusNotFound)
case err != nil:
fmt.Println(" log:", err)
http.Error(w, "internal error", http.StatusInternalServerError)
default:
fmt.Fprintf(w, "placed, total %v\n", total)
}
})
}
Run it (from the folder with these files; go.mod says module shop, go 1.24):
go test -v ./...
go run .
Output:
$ go test -v ./...
? shop [no test files]
? shop/httpapi [no test files]
=== RUN TestStockContract
--- PASS: TestStockContract (0.00s)
PASS
ok shop/memory 0.004s
=== RUN TestCartZeroValue
orders_test.go:13: total: Rs 160.00
--- PASS: TestCartZeroValue (0.00s)
PASS
ok shop/orders 0.002s
$ go run .
dish=dosa&qty=2 -> 200 placed, total Rs 120.00
dish=dosa&qty=2 -> 409 sorry, not enough left
dish=idli&qty=1 -> 404 no such dish
Design notes:
ordersimports onlyerrorsandfmt. Everything that touches the outside world lives inmemoryandhttpapi.TestStockContractuses the adapter only through theorders.Stockinterface. Copy it into asqlitepackage, change one line to build the SQLite adapter, and you know both behave the same.Cartis used withvar c Cart: its zero value is useful.- The handler checks input first (400), then maps each domain error to its own status.
Common mistakes (and the real messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
using orders.priceOf from main |
name priceOf not exported by package orders |
small first letter = unexported | export it if it's part of the API, or keep it inside |
| a struct holding a nil map | panic: assignment to entry in nil map |
zero value not useful | lazy init in the method, or a documented constructor |
amounts as plain int |
Rs 1.50 moved instead of Rs 150, no error | units not in the type | type Paise int64, type Rupees int64 |
| mixing domain types | cannot use Rupees(150) (constant 150 of int64 type Rupees) as Paise value in argument to Transfer |
(the compiler doing its job) | explicit conversion: Rupees(150).Paise() |
models ↔ services |
import cycle not allowed |
packages by layer | packages by feature |
http.Error(w, err.Error(), 500) |
DB host and user shown to customers | raw errors at the edge | map known errors, log the rest, generic 500 |
adding Refund to Gateway |
upiGateway does not implement payments.Gateway (missing method Refund) |
breaking API change | a new optional interface + type assertion |
orders.OrderService, GetOwner, appId, this |
(compiles) reviewers ask for changes | not idiomatic | orders.Service, Owner, appID, o |
IOrderService + OrderServiceImpl + factory |
four types for one thing | over-abstraction | one struct and NewService |
Practice
- Rename these to idiomatic Go, assuming each lives in the package shown:
user.UserData,func (self *Cart) GetItemCount() int,const MAX_RETRY = 3,var userId string,type HttpClient struct,package string_utils. type Queue struct{ items []string }. Is its zero value useful forPushandPop? Why is a slice different from a map here?- Write
type Kilometres float64andtype Miles float64and a functionFuelFor(d Kilometres) Litres. What happens if you call it with aMilesvalue? - Your
orderspackage needs to send an SMS when an order is placed. Where does theNotifierinterface go, and where does the Twilio-like gateway code go? - A library exports
type Store interface{ Get(id string) (Item, error) }. You want to add batch reads. Give a compatible design. - Your handler does
http.Error(w, err.Error(), 500)and the error ispq: password authentication failed for user "shop_admin". What leaks, and what should the client see?
Solutions
1. user.Data (better: a name that says what it holds, like user.Profile), func (c *Cart) ItemCount() int, const maxRetry = 3 (or MaxRetry if it must be exported), var userID string, type HTTPClient struct, and package strutil (better still: a package named for what the code does, not a utils bag).
2. Yes. append works on a nil slice (it allocates), and len of a nil slice is 0, so Push with q.items = append(q.items, s) and a Pop that checks len(q.items) == 0 both work on var q Queue. A nil map can be read but not written; a nil slice can be appended to.
3. A compile error (real run):
$ go run .
# shop
./main.go:13:25: cannot use m (variable of float64 type Miles) as Kilometres value in argument to FuelFor
Add func (m Miles) Kilometres() Kilometres { return Kilometres(m * 1.609344) } and convert explicitly.
4. The interface is a port: it goes in orders, next to the code that calls it, with only the method it needs (Notify(phone, msg string) error). The gateway code is an adapter in its own package (say smsgateway), which implements the interface; main wires it in.
5. Keep Store as it is and add an optional interface:
type BatchGetter interface {
GetMany(ids []string) ([]Item, error)
}
func GetMany(s Store, ids []string) ([]Item, error) {
if b, ok := s.(BatchGetter); ok {
return b.GetMany(ids)
}
items := make([]Item, 0, len(ids)) // fall back to one at a time
for _, id := range ids {
it, err := s.Get(id)
if err != nil {
return nil, err
}
items = append(items, it)
}
return items, nil
}
6. The database driver, the fact that password authentication is used, and the user name shop_admin: useful to an attacker. The client should see 500 internal error; the full error goes into the server's log, once.
Quick quiz
1. Which is idiomatic Go, in package orders? (From the video.)
- A.
type OrderService struct{}; func (this *OrderService) GetTotal() - B.
type Service struct{}; func (s *Service) Total() - C.
type order_service struct{}; func (self *order_service) get_total() - D.
type IService interface{}; type ServiceImpl struct{}
Answer
B. orders.Service has no stutter, the receiver s is short, and Total is a getter without Get. A stutters and uses this and Get; C uses underscores and self; D adds an I prefix and an Impl type for no reason.
2. Which of these types have a useful zero value? bytes.Buffer, sync.Mutex, map[string]int, strings.Builder, *sql.DB.
Answer
bytes.Buffer, sync.Mutex and strings.Builder. A nil map panics on write; a nil *sql.DB must be created with sql.Open.
3. In hexagonal architecture, which way do imports point?
Answer
Inward: adapters (httpapi, memory, postgres) import the core (orders); the core imports no adapter. main imports everything to wire it.
4. Is adding a method to an exported struct type a breaking change? And to an exported interface?
Answer
To a struct: no, existing code keeps compiling. To an interface: yes, every type that implemented the old interface no longer satisfies it (missing method ...).
Interview questions
- What does "idiomatic Go" mean to you? Simple, explicit code that follows the community's conventions (gofmt, Effective Go, Code Review Comments): MixedCaps names, small interfaces, errors as values, useful zero values, no unnecessary abstraction.
- How does Go decide what's exported? By the first letter of the identifier: upper case is exported from its package, lower case is not.
- What is stutter, and how do you avoid it? Repeating the package name in an identifier (
orders.OrderService). Name for how it reads at the call site:orders.Service. - What makes a zero value useful? Give examples. The type works without initialisation:
bytes.Buffer,sync.Mutex,strings.Builder. Achieve it with lazy init and sensible defaults when fields are zero. - Why prefer small interfaces? Easier to implement, combine and fake; they describe exactly what a consumer needs. "The bigger the interface, the weaker the abstraction."
- What are domain types and why use them? Defined types like
PaiseorAccountIDthat carry meaning; the compiler then rejects mix-ups between values with the same underlying type. - Package by layer or by feature? By feature, generally: cohesive packages, names that say what's inside, fewer import cycles.
- Why does Go forbid import cycles? For fast, simple builds and clear dependency direction; the compiler can build packages in order. A cycle signals that two packages are really one, or that a shared type should move.
- Explain hexagonal architecture. Core business logic in the middle with no technology dependencies, ports (interfaces) it owns, adapters that implement or drive them; dependencies point inward, making the core testable and adapters swappable.
- How should errors cross a boundary? Domain errors from the core, recognised with
errors.Is/Asand translated per protocol at the adapter; unknown errors become a generic message, with details logged once. - How do you evolve an interface without breaking users? Don't add methods; add a new optional interface and detect it with a type assertion (like
io.WriterTo). For real breaks, a new major version (/v2). - When is an abstraction too much? When it has one implementation and no test needs to replace it:
IService+ServiceImpl+ factory.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Idiomatic Go | code written the way experienced Go programmers write it | orders.Service, if err != nil |
| Convention | a shared habit everyone follows, not a compiler rule | MixedCaps names |
| Proverb | a short saying carrying wisdom | "Clear is better than clever." |
| Go proverbs | Rob Pike's sayings about Go design (Gopherfest 2015) | "Make the zero value useful." |
| Abstraction | hiding details behind a simpler idea | io.Reader hides files, sockets, strings |
| MixedCaps | capital letters inside a multi-word name, no underscores | maxLength, OrderID |
| Exported / unexported | visible to other packages (capital first letter) / private to its package | Total / priceOf |
| API | the exported names other code depends on | payments.Gateway, payments.Pay |
| Stutter | repeating the package name in an identifier | orders.OrderService |
| Receiver | the variable before a method's name | o in func (o *Order) Total() |
| Getter / setter | methods that read / change a field | Owner(), SetOwner(x) |
| Initialism | a word made of first letters, kept in one case | URL, ID, HTTP → appID |
| -er interface | a one-method interface named after its method | Reader, Notifier |
| Scope | the part of the code where a name exists | a loop's i |
| Zero value | the value a variable has before you set it | 0, "", nil |
| Useful zero value | a type that works without any setup | var b bytes.Buffer |
| Nil map | a map variable that was never made; readable, but writing panics | var m map[string]int |
| Lazy initialisation | creating something the first time it's needed | if t.counts == nil { t.counts = map[...]... } |
| Constructor | a function that builds a value | NewService(s) |
| Small interface | an interface with one or a few methods | Stock with Take |
| Accept interfaces, return structs | take the small interface you need, return concrete types | NewService(s Stock) *Service |
| Domain | the real-world business area the code is about | orders, money, stock |
| Domain type | a defined type named after a business idea | type Paise int64 |
| Defined type | a new named type with its own identity | type Rupees int64 |
| Underlying type | the type a defined type is built on | int64 for Paise |
| Paise / rupee | Indian money: 100 paise = 1 rupee | Paise(15000) = Rs 150 |
fmt.Stringer |
the interface with String() string, used by fmt to print |
Paise prints Rs 350.00 |
| Package by layer | packages split by kind of code | models/, services/ |
| Package by feature | packages split by what the code does | orders/, stock/ |
| Import cycle | packages importing each other (forbidden in Go) | models ↔ services |
internal/ |
a folder whose packages only the parent module can import | shop/internal/orders |
| Architecture | how a program is split into parts and how they depend on each other | core + adapters |
| Hexagonal architecture / ports and adapters | core logic in the middle, connected to the world by ports and adapters | orders + memory + httpapi |
| Core | the business rules, free of technology details | orders.Service.Place |
| Port | an interface the core owns that says what it needs | orders.Stock |
| Adapter | code connecting the core to one technology | memory.Store, httpapi.New |
| Clean architecture | a related style: dependencies always point inward | httpapi imports orders, never the reverse |
| Dependency direction | which package imports which | adapters → core |
| Domain error | an error that means something to the business | orders.ErrOutOfStock |
| Boundary / edge | where the program meets the outside world | the HTTP handler |
| Error mapping | translating errors for the outside world | ErrOutOfStock → 409 |
| Contract test | one test every implementation of an interface must pass | TestStockContract |
| Over-abstraction | layers and interfaces with no real need | IOrderService + Impl + factory |
| Breaking change | a change that makes existing users' code fail | adding Refund to Gateway |
| Optional interface | a separate interface checked with a type assertion | payments.Refunder, io.WriterTo |
| Type assertion | asking an interface value whether it holds another type or interface | r, ok := g.(Refunder) |
| Semantic versioning | MAJOR.MINOR.PATCH; a breaking change bumps MAJOR | v1.4.2 → v2.0.0 |
| Major version suffix | Go modules put v2+ in the import path | example.com/payments/v2 |
| Go 1 compatibility promise | Go 1 programs keep compiling with later Go 1.x releases | episode 2 |
Summary
- Idiomatic Go follows the community's conventions, guided by the Go proverbs: clear over clever, small interfaces, useful zero values, a little copying over a little dependency, errors as values, don't panic.
- Names: MixedCaps; capital = exported (
name priceOf not exported by package orders); lower-case one-word packages, noutils; no stutter (orders.Service); short consistent receivers;Owner()notGetOwner();URL/ID;-erinterfaces. - Useful zero values:
bytes.Bufferandsync.Mutexjust work; a struct with a nil map panics until lazy initialisation fixes it. - Domain types (
Paise,Rupees,AccountID) turn a silent Rs 1.50-instead-of-Rs 150 bug into a compile error. - Package by feature, not by layer: layers import each other until
import cycle not allowed. - Hexagonal architecture: a core with ports, adapters around it, dependencies pointing inward; errors are mapped at the boundary (409, 500), details stay in the log.
- Just enough abstraction: no
IService+Impl+ factory. - API stability: export less; adding a method to an exported interface breaks implementers (
missing method Refund); add a new optional interface instead, or a new major version.
Next episode: Building, releasing and containerising Go apps: go build flags, version injection with -ldflags -X, static binaries with CGO_ENABLED=0, build constraints, -trimpath, reproducible builds, Docker multi-stage builds, distroless, GoReleaser and CI.