Function Grouping and Ordering

  • Functions should be sorted in rough call order.
  • Functions in a file should be grouped by receiver. Therefore, exported functions should appear first in a file, afterstruct, const, var definitions.

A newXYZ()/NewXYZ() may appear after the type is defined, but before therest of the methods on the receiver.

Since functions are grouped by receiver, plain utility functions should appeartowards the end of the file.

BadGood
  1. func (s something) Cost() {
  2. return calcCost(s.weights)
  3. }
  4. type something struct{ }
  5. func calcCost(n []int) int {…}
  6. func (s something) Stop() {…}
  7.  
  8. func newSomething() something {
  9. return &something{}
  10. }
  1. type something struct{ }
  2.  
  3. func newSomething() something {
  4. return &something{}
  5. }
  6.  
  7. func (s something) Cost() {
  8. return calcCost(s.weights)
  9. }
  10. func (s something) Stop() {…}
  11.  
  12. func calcCost(n []int) int {…}