liveBook · Manning

Idiomatic coding style

As explained in Go by Example

A programming idiom is a customary way of expressing a solution or structure in a particular programming language.

Idiomatic Go is the community’s customary way of writing Go: established conventions aligned with the language’s design principles. Its purpose is not to justify every convention, but to give projects a consistent tone and make code clear, effective, efficient, maintainable, explicit, pragmatic, and straightforward to test. section 1.1.2

Writing idiomatically requires learning Go’s philosophies and mechanics rather than forcing habits from other languages onto the language. Prefer solving present problems plainly over speculative abstractions, and treat simplicity as a demanding design goal. section 1.1.2 section 1.1

Idiomatic choices include:

  • Name packages and their items according to Go conventions. section 2.2
  • Handle errors deliberately and decide carefully when struct fields should be exported. section 2.2
  • Satisfy standard-library interfaces when practical to integrate with standard-library and third-party functionality. section 2.2.4
  • Use tests, table-driven tests, subtests, and example tests to support maintainability and runnable documentation. section 2.0

A URL type that implements Stringer

A URL parser package can define String with a pointer receiver so *URL satisfies fmt.Stringer. Passing a *URL to fmt.Println then calls String automatically; passing a URL value does not, because an interface holding the nonpointer value cannot call its pointer-receiver methods. section 2.2.4

type Stringer interface { #1
    String() string #2
}

The Stringer interface shows the small contract a type fulfills to participate in fmt-based formatting. section 2.2.4

How Go by Example covers it

How deep it goes
Introduces idiomatic goals and identifies naming, errors, exports, interfaces, and testing as continuing areas of practice.
Examples
Demonstrates a URL parser package whose *URL type implements fmt.Stringer for automatic fmt.Println formatting.
What it assumes
Assumes Go variables, pointers, methods, interfaces, and module initialization; directs newcomers to a primer for these topics.
What you can do after
Apply it via Go conventions to write clearer, more maintainable, and more testable code.
How it connects
Connects idiomatic Go with naming conventions, error handling, exported fields, standard library interfaces, testing, composition, and goroutines.

Also explained in

Compare how 3 books explain idiomatic coding style →

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.