This specification aims to provide a code specification guidance for daily Go project development, facilitate the team to form a unified code style, and improve the readability, standardization and unity of the code. This specification will explain naming conventions, annotation conventions, code styles, and common tools provided by the Go language. The specification makes reference to the official code of the GO language.

First, naming conventions

Naming is a very important part of the code specification. A unified naming rule is conducive to improving the readability of the code. Good naming can obtain enough information only through naming.

Go is named with the letters A to Z or A to Z or underscore, followed by zero or more letters, underscores, and numbers (0 to 9). Go does not allow punctuation such as @, $, and % in naming. Go is a case-sensitive programming language. So Manpower and Manpower are two different names.

  1. When naming (including constants, variables, fields, type, function, structure, etc.) begin with a capital letter, such as: Group1, then use the identifier of the object can be in the form of external package code used by (client program need the guide into the package), this is called export (like public in an object-oriented language);
  2. Names that begin with a lowercase letter are not visible outside the package, but they are visible and available throughout the package (like private in object-oriented languages)

1, package name: package

Keep the name of the package consistent with the directory, and try to use meaningful package names that are short, meaningful, and don’t conflict with the standard library. Package names should be lowercase words and do not use underscores or mixed case.

package demo

package mainCOPY
Copy the code

2. File naming

Use meaningful file names that are short and meaningful, should be lowercase words, and use underscores to separate words.

my_test.goCOPY
Copy the code

3. Structure naming

  • Use camelback nomenclature, and the first letter is either uppercase or lowercase based on access control

  • Struct declarations and initializations take multiple lines, such as the following:

    Struct {Username string Email string}

    // Multi-line initialization u := User{Username: “astaxie”, Email: “[email protected]”,} COPY

4. Interface naming

  • Naming rules basic and above structure type

  • The structure names of individual functions are suffixed with “er”, for example, Reader, Writer.

    type Reader interface { Read(p []byte) (n int, err error) } COPY

5. Variable naming

  • Like structures, variable names generally follow the hump method, with the first letter either uppercase or lowercase according to access control rules, but for unique nouns, follow the following rules:

    • If the variable is private and the first word of the noun is unique, use lower case, such as apiClient
    • In all other cases the noun should be written in its original form, such as APIClient, repoID, UserID
    • Example of error: UrlArray, should be written as UrlArray or UrlArray
  • If the variable type Is bool, the name should start with Has, Is, Can, or Allow

    var isExist bool var hasConflict bool var canManage bool var allowGitHook boolCOPY

6. Constant naming

Constants must be written in all uppercase letters and broken with underscores

Const APP_VER = "1.0" COPYCopy the code

If a constant is an enumerated type, you need to create the corresponding type:

type Scheme string

const (
    HTTP  Scheme = "http"
    HTTPS Scheme = "https"
)
COPY
Copy the code

7. Keywords

The list below shows reserved words in Go. These reserved words cannot be used as constants or variables or any other identifier name.

Second, the annotation

Go provides C-style /* */ block comments and C ++ style // line comments. Line comments are the norm; Block comments are primarily shown as package comments, but can be useful in expressions or disable a lot of code.

  • Single-line comments are the most common form of comment, and you can use single-line comments starting with // anywhere

  • Multiline comments, also called block comments, all end with a /

    Begin and end with

    /, and cannot be nested. Multi-line comments are generally used for package documentation or to comment block code snippets

The Godoc tool of GO language can generate documents according to annotations, which can automatically generate corresponding websites (Golang.org is directly generated by godoc tool). The quality of annotations determines the quality of generated documents. Each package should have a package comment, followed by a block comment before the package clause. For multi-file packages, package comments need to exist in only one file, any one of them. Package reviews should introduce packages and provide information about the package as a whole. It will appear first on the GODoc page and should set up the detailed documentation below.

Detailed instructions on how to write comments can be found at golang.org/doc/effecti…

1. Package comments

Each package should have a package comment, a block comment or line comment that precedes the package clause. If a package has multiple GO files, it only needs to appear in one go file (usually a file with the same name as the package). Package comments should contain the following basic information (in strict order, introduction, creator, and creation time) :

  • Basic introduction to the package (package name, Introduction)
  • Creator, format: Creator: RTX name
  • Creation time, format: Creation time: yyyyMMdd

An example of an annotation for the util package is shown below

Util package, which contains constants shared by the project and encapsulates common functions in the project. // Create time: 20190419COPYCopy the code

2. Structure (interface) comments

Each custom structure or interface should be annotated with a brief description of the structure, in the format “structure name, structure description” on the first line of the structure definition. At the same time, each member variable in the structure should have a description, which should be placed after the member variable (note alignment), as shown in the following example:

Type User struct{Username string // Username Email string // Email}COPYCopy the code

3. Function (method) comments

Each function, or method (called a method in a structure or interface), should be annotated, and the annotation of the function should include three aspects (written in this exact order) :

  • Format description: Start with the function name and separate the description with commas (,)
  • Parameter list: One parameter in each line, starting with a comma (,) to separate the description
  • Return value: One return value per row

The following is an example:

// NewtAttrModel, attribute data layer operation class factory method // parameter: // CTX: context information // return value: Func NewAttrModel(CTX * common.context) *AttrModel {}COPYCopy the code

4. Code logic comments

For some key positions of the code logic, or partial complex logic, need to have the corresponding logic explanation, convenient for other developers to read the code, example is as follows:

// Read the attributes from Redis in batches. For the ids that are not read, record them in an array. Prepare to read XXXXX XXXXXXX xxxxxxxCOPY from DBCopy the code

5. Comment style

Unified use of Chinese annotations, strictly use Spaces between Chinese and English characters, this is not only between Chinese and English, English and Chinese punctuation should be separated by Spaces, for example:

// Read the attributes from Redis in batches. If the id is not read, record it into an array, ready to read the COPY from DBCopy the code

Above Redis, ID, DB and other Chinese characters are separated by Spaces.

  • Single-line comments are recommended for all
  • As with the code specification, single-line comments should not be too long; no more than 120 characters are allowed.

Third, code style

1. Indent and fold

  • The indent can be formatted using gofmt (gofmt is TAB indent).
  • In terms of line folding, the maximum length of a line should not exceed 120 characters. If more than 120 characters are displayed, please use line breaks to keep the format elegant.

We use Goland development tool, can directly use the shortcut key: CTRL + Alt +L, can be.

2. The end of the statement

The Go language does not require a colon ending like Java does, and the default line is a single piece of data

If you intend to write multiple statements on the same line, they must be used;

3. Parentheses and Spaces

Parentheses and Spaces can also be formatted using gofmt (go enforces line breaks in open braces, and line breaks report syntax errors), with Spaces between all operators and operands.

// if a>0 {// if a>0 // if a>0 // if a>0 // if a>0 // if a>0 // if a>0 // if a>0 // if a>0 //Copy the code

4. Import specification

Import In the case of multiple lines, Goimports will automatically format you, but let’s go over the import specification here. If you’re importing a package into a file, the following format is recommended:

import (
    "fmt"
)COPY
Copy the code

If your package introduces three types of packages: library packages, in-app packages, and third-party packages, it is recommended to organize your package in the following way:

import (
    "encoding/json"
    "strings"

    "myproject/models"
    "myproject/controller"
    "myproject/utils"

    "github.com/astaxie/beego"
    "github.com/go-sql-driver/mysql"
)   COPY
Copy the code

There are sequential import packages, the different types are separated by Spaces, the first is a real standard library, the second is a project package, the third is a third-party package.

Do not import packages using relative paths in a project:

// This is bad import import ".. / net "/ / this is the right thing to do the import" github.com/repo/proj/src/net "COPYCopy the code

However, if you are importing other packages in this project, it is best to use a relative path.

5. Error handling

  • The principle of error handling is not to discard any calls that return err, do not use _ discard, must handle all. Error received, either return to ERR, or log

  • Return early: If an error occurs, return immediately

  • Try not to use Panic unless you know what you are doing

  • Error description in English must be lowercase without punctuation

  • A separate error stream is used for processing

    // If err! = nil { // error handling } else { // normal code }

    // If err! = nil { // error handling return // or continue, etc. } // normal code COPY

6, test,

The unit Test file name is example_test.go. The function name of the Test case must start with Test, for example: TestExample Each important function must be written first

Four, common tools

As mentioned above, GO language itself has made a lot of efforts in code standardization. Many restrictions are mandatory syntax requirements, such as no line breaks for opening braces, and errors will be reported if the referenced package or defined variable is not used. In addition, GO also provides many useful tools to help us standardize the code.

Gofmt can solve most formatting problems by using GofMT. Gofmt automatically formats the code to ensure that all go code is consistent with the official recommended format. Therefore, all formatting problems are subject to goFMT results.

Goimport We strongly recommend using GoImport, which adds auto-delete and import packages on top of Gofmt.

go get golang.org/x/tools/cmd/goimportsCOPY
Copy the code

The Go Vet tool can help us statically analyze all kinds of problems in our source code, such as redundant code, early return logic, struct tag compliance, etc.

go get golang.org/x/tools/cmd/vetCOPY
Copy the code

Use as follows:

go vet .
Copy the code