search
HomeBackend DevelopmentGolangA pan of coding standards in the Go language

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"
)

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,
}

4. 函数命名

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

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

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

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

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

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

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

5. 接口命名

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

type helloWorld interface {
    func Hello();
}

type SayHello helloWorld

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

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

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
  1. 如果是特别复杂的包,可单独创建 doc.go 文件说明

5.2 代码注释

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

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

// 单行注释

/*
多
行
注
释
*/

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

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

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

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

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

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

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

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

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

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

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

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

5.3 特别注释

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

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

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

6. 包的导入

单行的包导入

import "fmt"

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

import (
  "fmt"
  "os"
)

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

  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"
)

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!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
go语言有没有缩进go语言有没有缩进Dec 01, 2022 pm 06:54 PM

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

go语言为什么叫gogo语言为什么叫goNov 28, 2022 pm 06:19 PM

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

一文详解Go中的并发【20 张动图演示】一文详解Go中的并发【20 张动图演示】Sep 08, 2022 am 10:48 AM

Go语言中各种并发模式看起来是怎样的?下面本篇文章就通过20 张动图为你演示 Go 并发,希望对大家有所帮助!

tidb是go语言么tidb是go语言么Dec 02, 2022 pm 06:24 PM

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

go语言能不能编译go语言能不能编译Dec 09, 2022 pm 06:20 PM

go语言能编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言。对Go语言程序进行编译的命令有两种:1、“go build”命令,可以将Go语言程序代码编译成二进制的可执行文件,但该二进制文件需要手动运行;2、“go run”命令,会在编译后直接运行Go语言程序,编译过程中会产生一个临时文件,但不会生成可执行文件。

【整理分享】一些GO面试题(附答案解析)【整理分享】一些GO面试题(附答案解析)Oct 25, 2022 am 10:45 AM

本篇文章给大家整理分享一些GO面试题集锦快答,希望对大家有所帮助!

go语言是否需要编译go语言是否需要编译Dec 01, 2022 pm 07:06 PM

go语言需要编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言,也就说Go语言程序在运行之前需要通过编译器生成二进制机器码(二进制的可执行文件),随后二进制文件才能在目标机器上运行。

go语言怎么删除字符串字符go语言怎么删除字符串字符Dec 09, 2022 pm 07:19 PM

删除字符串的方法:1、用TrimSpace()来去除字符串空格;2、用Trim()、TrimLeft()、TrimRight()、TrimPrefix()或TrimSuffix()来去除字符串中全部、左边或右边指定字符串;3、用TrimFunc()、TrimLeftFunc()或TrimRightFunc()来去除全部、左边或右边指定规则字符串。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)