Skip to content

Instantly share code, notes, and snippets.

@r8d8
Last active April 13, 2018 14:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r8d8/a6c85fc5c5d0f78a5daca9485697bd72 to your computer and use it in GitHub Desktop.
Save r8d8/a6c85fc5c5d0f78a5daca9485697bd72 to your computer and use it in GitHub Desktop.
Golang code style

The code should be read sequentially from beginning to end as a good prose, for code it means grouping logic from main high-level concepts to particular low-level details. In the rest, we simply follow S.O.L.I.D principals.

Recommended way to organize the code:

Length limits (inspired by NASA C Style guide):

  • function body <= 60 loc (to be suitable for single screen)
  • source file <= 600 loc

Source layout:

package example

// list of packages to import
import (
	"fmt"
)

// list of constants
const (
	ConstExample = "Hello, World!"
)

// list of variables
var (
	ExportedVar    = 123
	nonExportedVar = "hidden"
)

// list of exported interfaces
type Interfaced interface {
	Read(p []byte) (n int, err error)
}

// list of general public (exported) functions
func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) {
	return 0, nil
}

// list of public (exported) functions grouped by types
func NewExample(label string) *Example {
	return &Example{label}
}

// main type(s), try to keep the lowest amount of structs per file when possible
type Example struct {
	Label string
}

// list of public (exported) methods grouped by types
func (ex *Example) Greeting() string {
	return fmt.Sprintf("Example: %s", u.Label)
}

// list of private (non-exported) methods grouped by types
func (ex *Example) dump() string {
	return dump(ex)
}

// list of generic private functions
func dump(ins interface{}) string {
	return fmt.Sprintf("%#v", ins)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment