[Golang] Conventions

Tags
Golang
Engineering
Created
Nov 7, 2023 04:46 AM
Edited
Nov 6, 2023
Description
Comment/naming/interface/var… conventions

Commentary

  • Use C-style /**/ or C++-style //
  • Every package should have a package comment (either /**/ or // works)
    • Start with “Package <name>”
    • If multi-file package, add comments to any one of them
/*
Package regexp implements a simple library for regular expressions.

The syntax of the regular expressions accepted is:

    regexp:
        concatenation { '|' concatenation }
    concatenation:
        { closure }
    closure:
        term [ '*' | '+' | '?' ]
    term:
        '^'
        '$'
        '.'
        character
        '[' [ '^' ] character-ranges ']'
        '(' regexp ')'
*/
package regexp
  • Every exported name should have a doc comment including variable
    • Start with “<exported name> ...”
// Compile parses a regular expression and returns, if successful,
// a Regexp that can be used to match against text.
func Compile(str string) (*Regexp, error) {

Name

Package names

  • A package name is the accessor of its contents
import "bytes"
bytes.Buffer
  • lower case and single-word
  • no underscore or mixedCaps
  • A package name is the base name of its source directory like import "encoding/base64" // src/encoding/base64
  • Avoid import .
  • Use package structure to choose good names
// To call a constructor of ring.Ring, but it repeats itself
ring.NewRing // bad
ring.New // good

Getters

  • Don’t do GetName.
owner := obj.Owner() // not obj.GetOwner()
if owner != user {
	obj.SetOwner(user) // however, we use obj.SetOwner()
}

Interface names

  • One-method interfaces are named followed by “er” at the end like Reader, Writer, Formatter, and CloseNotifier
  • Avoid common ones like Read, Write, Close, Flush, and String, unless yours have the same signature and meaning

MixedCaps

  • or mixedCaps
  • No underscore

Semicolons

  • No need to include ; in the source, but it will be inserted by lexer
  • Semicolons are only used for separation one line

Source