Implementation of coding specification of golang language

Time:2020-9-30

The purpose of this specification is to provide a code specification guide for daily go project development, facilitate the team to form a unified code style, and improve the readability, normalization and uniformity of code. This specification will make a description from naming specification, annotation specification, code style and common tools provided by go language. The specification refers to the style of go official code.

1、 Nomenclature

Naming is an important part of code specification. Uniform naming rules can improve the readability of code. Good naming can get enough information only by naming.

Go is named with the letters a to Z or a to Z or underscores 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.

When the name (including constant, variable, type, function name, structure field, etc.) begins with a capital letter, such as group1, then the object with this form of identifier can be used by the code of external package (the client program needs to import the package first), which is called export (like public in object-oriented language);
Names that start with a lowercase letter are invisible outside the package, but they are visible and available inside the package (like private in object-oriented languages)

1. Package name: package

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


package demo
package main

2. File naming

Try to take meaningful file name, short, meaningful, should be lowercase words, use underline to separate each word.


my_test.go

3. Structure naming

Hump naming method is adopted, and the initial letter is in upper or lower case according to access control
The struct declaration and initialization format uses multiple lines, such as the following:

//Multi line statement
type User struct{
  Username string
  Email   string
}

//Multiline initialization
u := User{
  Username: "astaxie",
  Email:  "[email protected]",
}

4. Interface naming

Naming rules basic and structure type above
The structure name of a single function is suffixed with “Er”, such as reader, writer.


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

5. Variable naming

Similar to the structure, variable names generally follow the hump method, and the initial letter is capitalized or lowercase according to the access control principle. However, when special nouns are encountered, the following rules should be followed:

  • If the variable is private and the unique noun is the first word, use lowercase, such as apiclient
  • In other cases, the original wording of the noun should be used, such as apicclient, repoid, and userid
  • Error example: 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 bool

6. Constant naming

Constants should be made up of all uppercase letters and underlined participles


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 (
  HTTP Scheme = "http"
  HTTPS Scheme = "https"
)

7. Keywords

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

2、 Notes

Go provides C-style / * * / block comments and C + + style / / line comments. Line comments are normal; block comments are mostly shown as package comments, but are useful in expressions or disable a lot of code.

  • Single line comments are the most common form of comment. You can use single line comments starting with / / anywhere
  • Multiline comments, also known as block comments, begin with / * and end with * /, and cannot be nested. Multiline comments are generally used for document description of packages or code fragments annotated into blocks

The godoc tool of go language can generate documents according to the comments, and generate the corresponding website automatically( golang.org The quality of comments determines the quality of the generated documents. Each package should have a package comment with a block comment before the package clause. For multiple packages, package annotations only need to exist in one file, any one of them can. Package reviews should introduce packages and provide information about the entire package. It will first appear on the godoc page, and the following detailed documentation should be set up.

Detailed how to write notes can be done
reference resources: http://golang.org/doc/effective_ go.html#commentary

1. Package comments

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

  • Basic introduction of package (package name, introduction)
  • Creator, format: Creator: RTX name
  • Creation time, format: creation time: yyyymmdd

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

//Util package, which contains some constants shared by the project and encapsulates some common functions in the project.
//Created by: Hanru
//Creation time: 20190419

2. Structure (Interface) notes

Each user-defined structure or interface should have a comment description, which briefly introduces the structure and is placed on the line before the definition of structure. The format is: structure name and structure description. At the same time, each member variable in the structure must have a description, which is placed after the member variable (pay attention to alignment). Examples are as follows:

//User, the user object, defines the basic information of the user
type User struct{
  Username string // user name
  Email string // email
}

3. Function (method) annotation

Each function or method (the function under the structure or interface is called a method) should be annotated. The function annotation should include three aspects (written in strict accordance with this order)

  • Brief description, format description: start with function name and separate description with “,”
  • Parameter list: one parameter for each line. The parameter name begins with “,” separating the description part
  • Return value: one return value per line

Examples are as follows:

//Newtattrmodel, factory method of attribute data layer operation class
//Parameters:
//CTX: context information
//Return value:
//Property operation class pointer
func NewAttrModel(ctx *common.Context) *AttrModel {
}

4. Code logic annotation

For the code logic in some key positions or locally complex logic, corresponding logic description is required to facilitate other developers to read the code. Examples are as follows:

//Read the attributes from redis in batch. For the ID that has not been read, it will be recorded into an array and ready to be read from DB
xxxxx
xxxxxxx
xxxxxxx

5. Annotation style

Chinese annotations should be used uniformly. Spaces should be strictly used between Chinese and English characters. This is not only between Chinese and English, but also between English and Chinese punctuation points. For example:

//Read the attributes from redis in batch. For the ID that has not been read, it will be recorded into an array and ready to be read from DB

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

  • Single line comments are recommended
  • As with the code specification, single line comments should not be too long and should not exceed 120 characters.

3、 Code style

1. Indent and wrap

  • Indentation can be directly formatted with gofmt tool (gofmt is indented with tab);
  • In terms of line break, the maximum length of a line is not more than 120 characters. Please use the line break display to keep the format elegant as far as possible.

We use GoLand development tools, you can directly use the shortcut key: Ctrl + Alt + L, you can.

2. End of statement

In go language, there is no need for Java to end with a colon. By default, a line is a piece of data

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

3. Brackets and spaces

In terms of brackets and spaces, you can also directly use the gofmt tool to format (go will force the left brace not to wrap, and newlines will report syntax errors). Spaces should be left between all operators and operands.

//The right way
if a > 0 {

} 

//The wrong way
If a > 0 // A, there should be a space between 0 and >
{// the left curly bracket cannot wrap. A syntax error will be reported

}

4. Import specification
Import in the case of multiple lines, goimports will automatically help you format, but here we still standardize some import specifications, if you are in a file

If a package is introduced, the following format is recommended:


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 as follows:


import (
  "encoding/json"
  "strings"

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

  "github.com/astaxie/beego"
  "github.com/go-sql-driver/mysql"
)  

The first is real standard library, the second is project package, the third is third-party package.

Do not use relative paths to introduce packages in a project:

//This is a bad import
import “../net”

//This is the right thing to do
import “github.com/repo/proj/src/net”

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

5. Error handling

The principle of error handling is that you cannot discard any call that returns err. Do not use_ Discard, all must be disposed of. When an error is received, either err is returned or log is used to record it
Return as soon as possible: return as soon as an error occurs
Try not to use panic unless you know what you’re doing
If the error description is in English, it must be lowercase without punctuation
Independent error flow is used for processing

//Wrong way of writing
if err != nil {
  // error handling
} else {
  // normal code
}

//Correct writing
if err != nil {
  // error handling
  return // or continue, etc.
}
// normal code

6. Testing

The naming standard of unit test file name is example_ test.go
The function name of the test case must begin with test, for example: testexample
Each important function must first write test cases, test cases and formal code together to facilitate regression testing

4、 Common tools

As mentioned above, go language has made a lot of efforts in code normalization. Many restrictions are mandatory syntax requirements. For example, if the left curly bracket does not wrap, if the referenced package or defined variable is not used, an error will be reported. In addition, go also provides many useful tools to help us standardize the code,

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

goimport
We strongly recommend using goimport, which adds automatic deletion and import packages to gofmt


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

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


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

Use as follows:


go vet .

This article on the implementation of the golang language coding specification is introduced here. For more related content of the golang language coding specification, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!

Recommended Today

Comparison and analysis of Py = > redis and python operation redis syntax

preface R: For redis cli P: Redis for Python get ready pip install redis pool = redis.ConnectionPool(host=’39.107.86.223′, port=6379, db=1) redis = redis.Redis(connection_pool=pool) Redis. All commands I have omitted all the following commands. If there are conflicts with Python built-in functions, I will add redis Global command Dbsize (number of returned keys) R: dbsize P: print(redis.dbsize()) […]