A pan of coding standards in the Go language

Release: 2023-07-24 17:45:24
forward
1188 people have browsed it

Each language has its own unique coding standards. Learning the naming standards of that language can make the code you write more readable and less prone to low-level errors.

Based on personal coding habits and some articles on the Internet, this article has compiled some coding standards that everyone can use. They may be some mainstream solutions, but they do not represent the official ones. Let me state this first.

1. File naming

  1. Since file names on the Windows platform are not case-sensitive, file names should always be used Lower case

  2. Use underscores to separate different words, do not use camel case naming

  3. If it is a test file, you can use _test. go ends with

  4. If the file has platform characteristics, it should be named with filename_platform.go, such as utils_ windows.go, utils_linux.go, available The platforms include: windows, unix, posix, plan9, darwin, bsd, linux, freebsd, nacl, netbsd, openbsd, solaris, dragonfly, bsd, notbsd, android, stubs

  5. Generally, the main entry of the application should be main.go, or named in all lowercase of the application. For example, the entrance to MyBlog can be myblog.go

2. Constant naming

Currently On the Internet, you can see that there are two main styles of writing

  1. . The first is the camel case naming method, such as appVersion

  2. The second type uses all capital letters and uses underscores to segment words, such as APP_VERSION

There is no better or weaker of these two styles. You can choose freely. I Personally, I prefer to use the second one, mainly because it can be distinguished from variables at a glance.

If you want to define multiple variables, please use brackets to organize them.

const (
  APP_VERSION = "0.1.0"
  CONF_PATH = "/etc/xx.conf"
)
Copy after login

3. Variable naming

Different from constants, the naming of variables is more consistent among developers and should be used uniformlyCamel case naming

  1. In a relatively simple environment (small number of objects and strong targeting), the complete word can be abbreviated to a single letter, for example: user is written as u

  2. 若该变量为 bool 类型,则名称应以 Has, Is, CanAllow 开头。例如:isExist ,hasConflict 。

  3. 其他一般情况下首单词全小写,其后各单词首字母大写。例如:numShips 和 startDate 。

  4. 若变量中有特有名词(以下列出),且变量为私有,则首单词还是使用全小写,如 apiClient

  5. 若变量中有特有名词(以下列出),但变量不是私有,那首单词就要变成全大写。例如:APIClientURLString

这里列举了一些常见的特有名词:

// A GonicMapper that contains a list of common initialisms taken from golang/lint
var LintGonicMapper = GonicMapper{
    "API":   true,
    "ASCII": true,
    "CPU":   true,
    "CSS":   true,
    "DNS":   true,
    "EOF":   true,
    "GUID":  true,
    "HTML":  true,
    "HTTP":  true,
    "HTTPS": true,
    "ID":    true,
    "IP":    true,
    "JSON":  true,
    "LHS":   true,
    "QPS":   true,
    "RAM":   true,
    "RHS":   true,
    "RPC":   true,
    "SLA":   true,
    "SMTP":  true,
    "SSH":   true,
    "TLS":   true,
    "TTL":   true,
    "UI":    true,
    "UID":   true,
    "UUID":  true,
    "URI":   true,
    "URL":   true,
    "UTF8":  true,
    "VM":    true,
    "XML":   true,
    "XSRF":  true,
    "XSS":   true,
}
Copy after login

4. 函数命名

  1. 函数名还是使用 驼峰命名法

  2. 但是有一点需要注意,在 Golang 中是用大小写来控制函数的可见性,因此当你需要在包外访问,请使用 大写字母开头

  3. 当你不需要在包外访问,请使用小写字母开头

另外,函数内部的参数的排列顺序也有几点原则

  1. 参数的重要程度越高,应排在越前面

  2. 简单的类型应优先复杂类型

  3. 尽可能将同种类型的参数放在相邻位置,则只需写一次类型

5. 接口命名

使用驼峰命名法,可以用 type alias 来定义大写开头的 type 给包外访问。

type helloWorld interface {
    func Hello();
}

type SayHello helloWorld
Copy after login

当你的接口只有一个函数时,接口名通常会以 er 为后缀

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

5. 注释规范

注释分为

5.1 包注释

  1. 位于 package 之前,如果一个包有多个文件,只需要在一个文件中编写即可

  2. 如果你想在每个文件中的头部加上注释,需要在版权注释和 Package前面加一个空行,否则版权注释会作为Package的注释。

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package net
Copy after login
  1. 如果是特别复杂的包,可单独创建 doc.go 文件说明

5.2 代码注释

用于解释代码逻辑,可以有两种写法

单行注释使用 // ,多行注释使用 /* comment */

// 单行注释

/*
多
行
注
释
*/
Copy after login

另外,对于代码注释还有一些更加苛刻的要求,这个看个人了,摘自网络:

  • 所有导出对象都需要注释说明其用途;非导出对象根据情况进行注释。

  • 如果对象可数且无明确指定数量的情况下,一律使用单数形式和一般进行时描述;否则使用复数形式。

  • 包、函数、方法和类型的注释说明都是一个完整的句子。

  • 句子类型的注释首字母均需大写;短语类型的注释首字母需小写。

  • 注释的单行长度不能超过 80 个字符。

  • 类型的定义一般都以单数形式描述:

    // Request represents a request to run a command.  type Request struct { ...
    Copy after login
  • 如果为接口,则一般以以下形式描述:

    // FileInfo is the interface that describes a file and is returned by Stat and Lstat.
    type FileInfo interface { ...
    Copy after login
  • 函数与方法的注释需以函数或方法的名称作为开头:

    // Post returns *BeegoHttpRequest with POST method.
    Copy after login
  • 如果一句话不足以说明全部问题,则可换行继续进行更加细致的描述:

    // Copy copies file from source to target path.
    // It returns false and error when error occurs in underlying function calls.
    Copy after login
  • 若函数或方法为判断类型(返回值主要为 bool 类型),则以 <name> returns true if 开头:

    // HasPrefix returns true if name has any string in given slice as prefix.
    func HasPrefix(name string, prefixes []string) bool { ...
    Copy after login

5.3 特别注释

  • TODO:提醒维护人员此部分代码待完成

  • FIXME:提醒维护人员此处有BUG待修复

  • NOTE:维护人员要关注的一些问题说明

6. 包的导入

单行的包导入

import "fmt"
Copy after login

多个包导入,请使用 () 来组织

import (
  "fmt"
  "os"
)
Copy after login

另外根据包的来源,对排版还有一定的要求

  1. 标准库排最前面,第三方包次之、项目内的其它包和当前包的子包排最后,每种分类以一空行分隔。

  2. 尽量不要使用相对路径来导入包。

import (
    "fmt"
    "html/template"
    "net/http"
    "os"

    "github.com/codegangsta/cli"
    "gopkg.in/macaron.v1"

    "github.com/gogits/git"
    "github.com/gogits/gfm"

    "github.com/gogits/gogs/routers"
    "github.com/gogits/gogs/routers/repo"
    "github.com/gogits/gogs/routers/user"
)
Copy after login

7. 善用 gofmt

除了命名规范外,Go 还有很多格式上的规范,比如

  1. 使用 tab 进行缩进

  2. 一行最长不要超过 80 个字符

因此在格式上的问题,你大部分都可以放心交由 gofmt 帮你调整。关于 gofmt 的文章还在写,应该这两天就会更新。你可以过两天再来看看。

The above is the detailed content of A pan of coding standards in the Go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Go语言进阶学习
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template