2. Coding specification of go language

Coding Standard

1. Naming Convention

Go names start with the letters a to Z or a to Z or an 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. Therefore, Manpower and manpower are two different names.

  1. When the name (including constants, variables, types, function names, structure fields, etc.) starts with an uppercase letter, such as: Group1, then the object using this form of identifier can be used by the code of the external package (the client program needs to import this package first), which is called export (like public in object-oriented languages);
  2. Names that start with a lowercase letter are not visible outside the package, but they are visible and available inside the entire package (like private in object-oriented languages)

1. Package naming: package

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

package demo

package main

2. File naming

Try to take a meaningful file name, short and meaningful, it should be lowercase words, use underscore to separate each word.

my_test.go

3. Structure naming

  • CamelCase is used, and the first letter is capitalized or lowercased according to access control

  • The struct declaration and initialization formats use multiple lines, such as the following:

// Multi-line statement
type User struct{<!-- -->
    Username string
    Email string
}

// multi-line initialization
u := User{<!-- -->
    Username: "astaxie",
    Email: "[email protected]",
}

4. Interface naming

  • Naming rules Basic and above structure types
  • Struct names for individual functions are suffixed with “er”, e.g. Reader , Writer .
type Reader interface {<!-- -->
        Read(p []byte) (n int, err error)
}

5. Variable naming

  • Similar to structures, variable names generally follow the camel case method, and the first letter is capitalized or lowercased according to the access control principle. However, when encountering unique nouns, the following rules need to be followed:
    • If the variable is private and the proper noun is the first word, use lowercase, such as apiClient
    • In other cases, the original wording of the noun should be used, such as APIClient, repoID, UserID
    • Error example: UrlArray, should be written as urlArray or URLArray
  • If the variable type is bool type, the name should start with Has, Is, Can or Allow
var isExist bool
var has Conflict bool
var can Manage bool
var allowGitHook bool

6. Constant naming

Constants must be composed of all uppercase letters and separated by underscores

const APP_VER = "1.0"

If it is a constant of enumeration type, you need to create the corresponding type first:

type Scheme string

const (
    HTTPScheme = "http"
    HTTPS Scheme = "https"
)

7. Keywords

The list below shows the reserved words in Go. These reserved words cannot be used as constant or variable or any other identifier names.

guanjianzi

2. Comments

Go provides C-style /* */ block comments and C++-style // line comments. Line comments are the norm; block comments appear primarily as package comments, but are useful in expressions or disable large amounts of code.

  • Single-line comments are the most common form of comments, you can use single-line comments starting with // anywhere
  • Multi-line comments are also called block comments, which start with /* and end with */, and cannot be nested. Multi-line comments are generally used for document descriptions of packages or code snippets commented into blocks

The godoc tool that comes with the go language can generate documents based on comments, and can automatically generate corresponding websites (golang.org is directly generated using the godoc tool). The quality of comments determines the quality of generated documents. Every package should have a package comment and a block comment before the package clause. For multi-file packages, the package annotation only needs to exist in one file, any one will do. Package reviews should introduce the package and provide information related to the package as a whole. It will first appear on the godoc page and should set the detailed documentation below.

Detailed how to write comments can be
Reference: http://golang.org/doc/effective_go.html#commentary

1. Package comment

Every 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 the file with the same name as the package). The package comment should contain the following basic information (please strictly follow this order, introduction, creator, creation time):

  • Basic profile of the package (package name, profile)
  • Creator, format: creator: rtx name
  • Creation time, format: Creation time: yyyyMMdd

For example, the comment example of the util package is as follows

// util package, this package contains some constants shared by the project, and encapsulates some common functions in the project.
// created by: hanru
// Creation time: 20190419

2. Structure (interface) annotation

Each custom structure or interface should have a comment. The comment briefly introduces the structure and is placed on the line before the structure definition. The format is: structure name, structure description. At the same time, each member variable in the structure must have a description, and the description should be placed behind the member variable (note the alignment). Examples are as follows:

// User, user object, defines the basic information of the user
type User struct{<!-- -->
    Username string // username
    Email string // Email
}

3. Function (method) annotation

Each function or method (the function under the structure or interface is called a method) should have a comment description, and the function comment should include three aspects (written strictly in this order):

  • Brief description, format description: start with the function name, “,” to separate the description part
  • Parameter list: one parameter per line, at the beginning of the parameter name, “,” separates the description part
  • Return value: one return value per line

Examples are as follows:

// NewtAttrModel , the factory method of the attribute data layer operation class
// parameters:
// ctx: context information
// return value:
// attribute operation class pointer
func NewAttrModel(ctx *common.Context) *AttrModel {<!-- -->
}

4. Code logic comment

For the code logic at some key positions, or some more complex logic, it is necessary to have a corresponding logic description to facilitate other developers to read the code, examples are as follows:

// send mail
xxxxx
xxxxxxxx
xxxxxxxx

5. Comment style

Uniformly use Chinese comments, and strictly use spaces to separate Chinese and English characters. This is not only between Chinese and English, but also between English and Chinese punctuation. For example:

// Send email to others, read the data in the form through the provided excel

The above email, excel and other Chinese characters are separated by spaces.

  • It is recommended to use single-line comments for all
  • Just like the code specification, single-line comments should not be too long, exceeding 120 characters is prohibited.

3. Code style

1. Indentation and line break

  • Indentation can be formatted directly with the gofmt tool (gofmt is indented with tabs);
  • In terms of line breaks, the maximum length of a line should not exceed 120 characters. If it exceeds, please use line breaks to keep the format as elegant as possible.

We use the Goland development tool, you can directly use the shortcut keys: ctrl + alt + L, that’s it.

2. The end of the statement

The Go language does not need a colon at the end similar to Java. By default, a row is a piece of data.

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

3, brackets and spaces

In terms of brackets and spaces, you can also use the gofmt tool to format directly (go will force the left brace not to wrap, and a syntax error will be reported if the line wraps), and spaces must be left between all operators and operands.

// correct way
if a > 0 {<!-- -->

}

// wrong way
if a>0 // a , there should be a space between 0 and >
{<!-- --> // The left curly brace cannot be wrapped, and a syntax error will be reported

}

4, import specification

In the case of import with multiple lines, goimports will automatically format it for you, but let’s standardize some import specifications here. If you import a package in a file, it is recommended to use the following format:

import (
    "fmt"
)

If your package introduces three types of packages, standard library package, program internal package, and third-party package, 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"
)

Introduce packages sequentially. Different types are separated by spaces. The first type is the actual standard library, the second is the project package, and the third is the third-party package.

Do not use relative paths to import packages in the project:

// This is a bad import
import "../net"

// this is the correct way
import "github.com/repo/proj/src/net"

But if you are introducing other packages in this project, it is best to use relative paths.

5. Error handling

  • The principle of error handling is that you cannot discard any calls that return err, do not use _ to discard, and all must be processed. When an error is received, either return err, or use log to record it
  • Return as soon as possible: Once an error occurs, return immediately
  • Try not to panic unless you know what you are doing
  • If the error description is in English, it must be in lowercase, and no punctuation is required at the end
  • Handling with a separate error stream
// wrong wording
if err != nil {<!-- -->
    // error handling
} else {<!-- -->
    // normal code
}

// Correct spelling
if err != nil {<!-- -->
    // error handling
    return // or continue, etc.
}
// normal code

6. Test

The unit test file name naming convention is example_test.go
The function name of the test case must start with Test, for example: TestExample
Every important function must first write a test case, and the test case is submitted together with the formal code for regression testing

4. Common tools

As mentioned above, the go language itself has made a lot of efforts in terms of code standardization. Many restrictions are mandatory grammatical requirements, such as no new line in the left curly brace, and an error will be reported if the referenced package or defined variable is not used. In addition Go still provides many useful tools to help us standardize the code,

gofmt
Most format problems can be solved by gofmt. gofmt automatically formats the code to ensure that all go codes are consistent with the officially recommended format. Therefore, all format-related problems are subject to the results of gofmt.

goimport
We strongly recommend using goimport , which adds automatic removal and import of packages to gofmt .

go get golang.org/x/tools/cmd/goimports

go vet
The vet tool can help us statically analyze various problems in our source code, such as redundant code, early return logic, whether the struct tag meets the standard, etc.

go get golang.org/x/tools/cmd/vet

Use as follows:

go vet .