5

golang推荐的命名规范

 1 year ago
source link: https://www.cnblogs.com/lori/p/17371276.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

二 golang推荐的命名规范

很少见人总结一些命名规范,也可能是笔者孤陋寡闻, 作为一个两年的golang 开发者, 我根据很多知名的项目,如 moby, kubernetess 等总结了一些常见的命名规范。
命名规范可以使得代码更容易与阅读, 更少的出现错误。

文件命名规范
由于文件跟包无任何关系, 而又避免windows大小写的问题,所以推荐的明明规范如下:

  • 文件名应一律使用小写
  • 不同单词之间用下划线分割
  • 命名应尽可能地见名知意

常量命名规范
常量明明用 camelcase来命名示例如下

const todayNews = "Hello"

// 如果超过了一个常量应该用括号的方法来组织

const (
systemName = "What"
sysVal = "dasdsada"
)

变量命名规范
与常量命名方式一样,变量也应该使用驼峰的命名方式, 但注意尽量不与包名一致或者以包名开头

var x string
x := new(string)

函数命名规范
由于Golang的特殊性(用大小写来控制函数的可见性),除特殊的性能测试与单元测试函数之外, 都应该遵循如下原则

  • 使用驼峰命名
  • 如果包外不需要访问请用小写开头的函数
  • 如果需要暴露出去给包外访问需要使用大写开头的函数名称
    一个典型的函数命名方法如下:
// 注释一律使用双斜线, 对象暴露的方法
func (*fileDao) AddFile(file *model.File) bool {
result := db.NewRecord(*file)
if result {
db.Create(file)
}
return result
}

// 不需要给包外访问的函数如下
func removeCommaAndQuote(content string) string {
re, _ := regexp.Compile("[\\`\\,]+")
return strings.TrimSpace(re.ReplaceAllString(content, ""))
}

接口命名规范
接口命名也是要遵循驼峰方式命名, 可以用 type alias 来定义大写开头的type 给包外访问

type helloWorld interface {
func Hello();
}

type SayHello helloWorld

Struct命名规范

  • 与接口命名规范类似

receiver 命名规范
golang 中存在receiver 的概念 receiver 名称应该尽量保持一致, 避免this, super,等其他语言的一些语义关键字如下

type A struct{}

func (a *A) methodA() {
}
func (a *A) methodB() {
a.methodA()
}

注释规范

  • 注释应一律使用双斜线

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK