每个语言都有自己特色的编码规范,学习该语言的命名规范,能让你写出来的代码更加易读,更加不容易出现一些低级错误。
本文根据个人编码习惯以及网络上的一些文章,整理了一些大家能用上的编码规范,可能是一些主流方案,但不代表官方,这一点先声明一下。
_test.go 结尾文件名_平台.go 命名,比如 utils_ windows.go,utils_linux.go,可用的平台有:windows, unix, posix, plan9, darwin, bsd, linux, freebsd, nacl, netbsd, openbsd, solaris, dragonfly, bsd, notbsd, android,stubsmyblog.go
目前在网络上可以看到主要有两种风格的写法
这两种风格,没有孰好孰弱,可自由选取,我个人更倾向于使用第二种,主要是能一眼与变量区分开来。
如果要定义多个变量,请使用 括号 来组织。
const (
APP_VERSION = "0.1.0"
CONF_PATH = "/etc/xx.conf"
)和常量不同,变量的命名,开发者们的喜好就比较一致了,统一使用 驼峰命名法
Has, Is, Can 或 Allow 开头。例如:isExist ,hasConflict 。apiClient。APIClient,URLString这里列举了一些常见的特有名词:
// 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,
}另外,函数内部的参数的排列顺序也有几点原则
使用驼峰命名法,可以用 type alias 来定义大写开头的 type 给包外访问。
type helloWorld interface {
func Hello();
}
type SayHello helloWorld当你的接口只有一个函数时,接口名通常会以 er 为后缀
type Reader interface {
Read(p []byte) (n int, err error)
}注释分为
// 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用于解释代码逻辑,可以有两种写法
单行注释使用 // ,多行注释使用 /* comment */
// 单行注释
/*
多
行
注
释
*/另外,对于代码注释还有一些更加苛刻的要求,这个看个人了,摘自网络:
go // Request represents a request to run a command. type Request struct { ...
go // FileInfo is the interface that describes a file and is returned by Stat and Lstat. type FileInfo interface { ...
go // Post returns *BeegoHttpRequest with POST method.
go // 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 开头:go // HasPrefix returns true if name has any string in given slice as prefix. func HasPrefix(name string, prefixes []string) bool { ...
单行的包导入
import "fmt"多个包导入,请使用 {} 来组织
import {
"fmt"
"os"
}另外根据包的来源,对排版还有一定的要求
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"
)除了命名规范外,Go 还有很多格式上的规范,比如
因此在格式上的问题,你大部分都可以放心交由 gofmt 帮你调整。关于 gofmt 的文章还在写,应该这两天就会更新。你可以过两天再来看看。
参考文章:
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/758/viewspace-3122516/ ,如需转载,请注明出处,否则将追究法律责任。