Subscribe

Writing idiomatic golang code

Ten habits that make Go code idiomatic, each shown with runnable code on Go 1.27: case for visibility, plain functions, grouped imports with goimports, early returns, wrapped errors, context first, doc comments, table tests, go vet and staticcheck.

"Idiomatic" gets thrown around a lot in Go code reviews. In practice it means a handful of habits that experienced Go developers share, so their code looks the same and reads the same. None of them are hard. Most of them are things the tools already check for you, if you run the tools.

In this blog we will go through ten of those habits with a small package that parses rupee prices, a program that uses it, and a couple of deliberately bad files that go vet and staticcheck complain about. Everything ran on Go 1.27.3. If you skipped the formatting part, read that first, because habit one is just "run gofmt".

💻 The full code for this tutorial is on GitHub: FenixAra/tutorials/Golang/writing-idiomatic-golang-code. Clone it and run each step yourself.

Setting up

One module, four small folders and a samples/ folder for the bad examples:

mkdir idiomatic && cd idiomatic
go mod init example.com/idiomatic
mkdir price shop earlyreturn ctxtimeout samples

The samples end in .go.txt so go vet ./... on the module stays clean. Copy one into a scratch folder as a .go file to try it.

1. Run gofmt

There is not much to say here that the last part didn't. Format on save, and add test -z "$(gofmt -l .)" to CI. Code that isn't gofmt'ed is the first thing a Go reviewer notices, actually even before reading what it does.

2. Case decides visibility

This is the naming rule that matters most, so it comes early. A name that starts with an uppercase letter is exported (visible outside its package); lowercase is private to the package. It applies to everything: functions, types, struct fields, methods, variables and constants. Constants are not special, by the way. Go uses MaxRetries, not MAX_RETRIES.

Here is the price package. Parse, Total, Format, Item and ErrEmpty start uppercase because shop needs them.

// Package price parses rupee amounts and adds up a cart.
// Amounts are kept in paise (int64) so we never round floats.
package price

import (
    "errors"
    "fmt"
    "strconv"
    "strings"
)

// ErrEmpty is returned by Parse for an empty string.
var ErrEmpty = errors.New("empty amount")

// Item is one line in a cart.
type Item struct {
    Name  string
    Paise int64
    Qty   int
}

// Parse turns "149.50" or "Rs 149.50" into paise (14950).
func Parse(s string) (int64, error) {
    s = strings.TrimSpace(strings.TrimPrefix(s, "Rs"))
    if s == "" {
        return 0, ErrEmpty
    }
    rupees, paise, hasDot := strings.Cut(s, ".")
    if len(paise) > 2 {
        return 0, fmt.Errorf("parse %q: more than 2 decimal places", s)
    }
    r, err := strconv.ParseInt(rupees, 10, 64)
    if err != nil {
        return 0, fmt.Errorf("parse %q: %w", s, err)
    }
    p := int64(0)
    if hasDot {
        p, err = strconv.ParseInt((paise + "0")[:2], 10, 64)
        if err != nil {
            return 0, fmt.Errorf("parse %q: %w", s, err)
        }
    }
    return r*100 + p, nil
}

// Total adds up the cart. It is a plain function: it needs no state.
func Total(items []Item) int64 {
    var sum int64
    for _, it := range items {
        sum += it.Paise * int64(it.Qty)
    }
    return sum
}

// Format prints paise as rupees, like "Rs 299.00".
func Format(paise int64) string {
    return fmt.Sprintf("Rs %d.%02d", paise/100, paise%100)
}

The next part, naming conventions, goes much deeper into names, so I'll leave it at this rule here.

3. Plain functions are fine

Total is a package level function. It doesn't need any state, so it doesn't hang off a struct. I still see code (mostly from people coming from Java) with an empty type PriceCalculator struct{} and a Calculate method on it, created with a NewPriceCalculator() just to call one function. In Go the package is already the namespace. price.Total(cart) reads fine on its own.

Use a method when the function really works on a value's data, like Item having a Subtotal() method. Otherwise, a function.

4. Group imports, standard library first

The convention is one block with standard library imports first, then a blank line, then everything else (third party and your own module). Here is samples/imports.go.txt with the imports thrown in any order:

import (
    "os"
    "example.com/idiomatic/price"
    "fmt"
    "errors"
)

gofmt only sorts within a block. It doesn't know which import is standard library:

$ gofmt -d imports.go
diff imports.go.orig imports.go
--- imports.go.orig
+++ imports.go
@@ -1,10 +1,10 @@
 package main

 import (
-   "os"
+   "errors"
    "example.com/idiomatic/price"
    "fmt"
-   "errors"
+   "os"
 )

 func main() {

goimports does know. With -local example.com it also puts your own module's imports in their own group:

$ go run golang.org/x/tools/cmd/goimports@v0.53.0 -local example.com -d imports.go
diff -u imports.go.orig imports.go
--- imports.go.orig
+++ imports.go
@@ -1,10 +1,11 @@
 package main

 import (
+   "errors"
+   "fmt"
    "os"
+
    "example.com/idiomatic/price"
-   "fmt"
-   "errors"
 )

 func main() {

In VS Code, gopls does this on save. The local setting is called "formatting.local" in the gopls settings, if you want your module grouped separately too.

5. Return early

Here is the same order check written twice in earlyreturn/main.go. First nested, the way a lot of beginners write it:

func checkNested(o order) error {
    if o.Qty > 0 {
        if o.Email != "" {
            if o.Qty <= 10 {
                return nil
            } else {
                return errors.New("max 10 per order")
            }
        } else {
            return errors.New("email is required")
        }
    } else {
        return errors.New("qty must be positive")
    }
}

And with early returns:

func check(o order) error {
    if o.Qty <= 0 {
        return errors.New("qty must be positive")
    }
    if o.Email == "" {
        return errors.New("email is required")
    }
    if o.Qty > 10 {
        return errors.New("max 10 per order")
    }
    return nil
}

Both give the same answers:

$ go run ./earlyreturn
order 1: nested=<nil> early=<nil>
order 2: nested=qty must be positive early=qty must be positive
order 3: nested=email is required early=email is required
order 4: nested=max 10 per order early=max 10 per order

The second one is easier to read because each error sits right next to the check that causes it. In the nested one, "qty must be positive" is at the very bottom, 13 lines away from o.Qty > 0. The happy path (return nil) stays at the left edge, at the end. This is the shape almost every Go function has: check, handle, return, and the normal flow keeps going down the left side.

6. Errors are values, wrap them

The shop program uses price.Parse and decides what to do with each kind of error. Its imports are grouped the way goimports left them.

// Command shop parses a few prices and prints a cart total.
package main

import (
    "errors"
    "fmt"
    "os"

    "example.com/idiomatic/price"
)

func main() {
    lines := [][2]string{{"pen", "10"}, {"notebook", "Rs 45.50"}, {"bag", "12.345"}, {"cap", ""}}
    var cart []price.Item
    for _, line := range lines {
        p, err := price.Parse(line[1])
        if errors.Is(err, price.ErrEmpty) {
            fmt.Println("skip", line[0]+": no price")
            continue
        }
        if err != nil {
            fmt.Fprintln(os.Stderr, "skip", line[0]+":", err)
            continue
        }
        cart = append(cart, price.Item{Name: line[0], Paise: p, Qty: 2})
    }
    fmt.Println(len(cart), "items, total", price.Format(price.Total(cart)))
}
$ go run ./shop
skip bag: parse "12.345": more than 2 decimal places
skip cap: no price
2 items, total Rs 111.00

ErrEmpty is a sentinel error, and errors.Is checks for it even when it's wrapped. Parse wraps the strconv errors with %w and adds the input, so the message says which value failed. Error strings start lowercase and have no full stop at the end, because they usually end up in the middle of another message. If you have doubts about when to wrap and when to return as is, the error handling tutorial covers this properly.

7. Context comes first

Anything that can block (an HTTP call, a database query, a slow lookup) should take a context.Context as its first parameter, named ctx. The caller then decides how long it's willing to wait.

// lookup pretends to call a slow service. ctx comes first, by convention.
func lookup(ctx context.Context, id int, cost time.Duration) (string, error) {
    select {
    case <-time.After(cost):
        return fmt.Sprintf("user-%d", id), nil
    case <-ctx.Done():
        return "", fmt.Errorf("lookup %d: %w", id, ctx.Err())
    }
}

func main() {
    for _, cost := range []time.Duration{50 * time.Millisecond, 300 * time.Millisecond} {
        ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
        start := time.Now()
        name, err := lookup(ctx, 7, cost)
        cancel()
        took := time.Since(start).Round(50 * time.Millisecond)
        fmt.Printf("cost %v: name=%q err=%v (took ~%v)\n", cost, name, err, took)
    }
}
$ go run ./ctxtimeout
cost 50ms: name="user-7" err=<nil> (took ~50ms)
cost 300ms: name="" err=lookup 7: context deadline exceeded (took ~100ms)

The 300 ms lookup gave up at the 100 ms deadline instead of making the caller wait. Always call cancel(), even when the call finished early (go vet warns you if you lose the cancel function). Don't store a context inside a struct either, pass it along.

8. Don't wrap one line in a function

A small one, and a bit of an opinion. A helper like func isEmpty(s string) bool { return s == "" } makes the reader jump to another place to learn nothing. s == "" is already clear. Make a function when it has a name that says more than its body, or when the same three or four lines show up in several places. A little copying is fine.

9. Document what you export

Every exported name gets a doc comment that starts with the name. go doc reads them straight from the source:

$ go doc ./price
package price // import "example.com/idiomatic/price"

Package price parses rupee amounts and adds up a cart. Amounts are kept in paise
(int64) so we never round floats.

var ErrEmpty = errors.New("empty amount")
func Format(paise int64) string
func Parse(s string) (int64, error)
func Total(items []Item) int64
type Item struct{ ... }
$ go doc ./price Parse
package price // import "example.com/idiomatic/price"

func Parse(s string) (int64, error)
    Parse turns "149.50" or "Rs 149.50" into paise (14950).

The package comment goes above package price, and it starts with "Package price". Comments should say why or what, not repeat the code line by line.

10. Test, then let the tools review

Tests sit next to the code in price_test.go. The Go style is a table: a slice of inputs and expected outputs, and one loop with t.Run for each.

func TestParse(t *testing.T) {
    tests := []struct {
        in      string
        want    int64
        wantErr bool
    }{
        {"149.50", 14950, false},
        {"Rs 20", 2000, false},
        {"0.5", 50, false},
        {"", 0, true},
        {"12.345", 0, true},
        {"abc", 0, true},
    }
    for _, tt := range tests {
        t.Run(tt.in, func(t *testing.T) {
            got, err := Parse(tt.in)
            if (err != nil) != tt.wantErr {
                t.Fatalf("Parse(%q) error = %v, wantErr %v", tt.in, err, tt.wantErr)
            }
            if got != tt.want {
                t.Errorf("Parse(%q) = %d, want %d", tt.in, got, tt.want)
            }
        })
    }
}
$ go test ./...
?       example.com/idiomatic/ctxtimeout    [no test files]
?       example.com/idiomatic/earlyreturn   [no test files]
ok      example.com/idiomatic/price 0.456s
?       example.com/idiomatic/shop  [no test files]

With -v you see each row as its own subtest. One thing I didn't expect: the empty string row shows up as TestParse/#00, because a subtest needs some name and "" gives none. If that bothers you, add a name field to the table.

For review, two tools catch a lot before a human looks. go vet comes with Go. staticcheck is a separate install and finds simpler ways to write things. Here is samples/lint.go.txt, which runs fine:

func validate(email string, admin bool) error {
    if strings.Index(email, "@") == -1 {
        return errors.New(fmt.Sprintf("Invalid email %q.", email))
    }
    if admin == true {
        fmt.Println("admin", email)
    }
    return nil
}

func main() {
    fmt.Println("checking %s", "a@example.com")
    fmt.Println(validate("a.example.com", false))
}
$ go run lint.go
checking %s a@example.com
Invalid email "a.example.com".
$ go vet lint.go
lint.go:20:2: fmt.Println call has possible Printf formatting directive %s
$ go install honnef.co/go/tools/cmd/staticcheck@v0.8.2
$ staticcheck lint.go
lint.go:10:5: should use !strings.Contains(email, "@") instead (S1003)
lint.go:11:10: should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (S1028)
lint.go:13:5: should omit comparison to bool constant, can be simplified to admin (S1002)

go vet itself found the real bug: Println with a %s that never gets filled in, which you can see in the output. staticcheck found three spots that work but aren't how Go is usually written. Neither tool complained about the error string starting with a capital and ending with a full stop, so that one is still on you in review. On the real module, both are quiet:

$ go vet ./...
$ staticcheck ./...

That's ten habits. Run both tools in CI next to the gofmt check and most of these get caught on their own.