liveBook · Manning

Style guide

As explained in Go by Example

A programming convention is a commonly accepted practice for organizing or expressing code within a language community.

A style guide is the shared set of conventions that gives Go code a consistent, idiomatic shape. Its purpose is not to justify every choice: some conventions have strong reasons, while others are simply established practice. Following them makes code easier to read, understand, maintain, test, and share across projects. section 1.1.2

Idiomatic style favors code that is simple, pragmatic, explicit, and testable. Prefer solving the current problem over adding speculative abstractions. Clear conventions also reduce personal-style debates, letting developers focus on behavior and design rather than formatting choices. section 1.1.2 section 2.2.1

Apply conventions where they clarify intent:

  • Choose package names that make exported identifiers meaningful together, such as url.Parse. section 2.2.1
  • Avoid stuttering in package APIs when the package name already supplies the context; accept an exception when a clearer alternative would be too generic or confusing. section 2.2.1
  • Use short variable names in small scopes and more descriptive names in broader scopes, provided surrounding context keeps their purpose clear. section 2.2.1
  • Use got, want failure messages so tests show received and expected values immediately. section 2.3.4
  • Print values with %#v when field-level Go-syntax output is needed, rather than formatting that invokes a String method. section 2.3.4
uri, err := url.Parse("https://github.com/inancgumus")

The package name supplies the domain context, allowing Parse to remain concise without becoming unclear or repetitive. section 2.2.1

Make failures explain themselves

A descriptive t.Errorf message labels the input, got value, and wanted value. This makes a failing parse test diagnosable without first opening the tested code. For complex nested values, cmp.Diff can produce a focused difference instead of requiring manual inspection. section 2.3.4

How Go by Example covers it

How deep it goes
Works through naming and diagnostic-test conventions, while deferring broader idioms for continued exploration.
Examples
Uses url.Parse, uri and u variable names, got/want error output, and cmp.Diff for URL comparisons.
What you can do after
Evaluate/understand idiomatic Go by judging simplicity, pragmatism, explicitness, testability, and consistency.
How it connects
Connects idiomatic Go to naming conventions, error handling, exported fields, standard library interfaces, gofmt, and testing.

Also explained in

Compare how 10 books explain style guide →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.