Go style guideline?

huangapple go评论69阅读模式
英文:

Go style guideline?

问题

我正在开始学习Go编程,我想问一下在编程时是否有一些可以遵循的模式,比如:

// 包

// 按重要性排序的结构体

// 结构体方法

// 未导出的方法

// 导出的方法

// 获取器和设置器

英文:

I'm starting in the programming with Go and I want to ask if there are some patterns to follow when programming, like:

// Package

// Structs orderer by importance

// Struct methods

// Un-exported methods

// Exported methods

// getters and setters

答案1

得分: 2

以下是翻译好的内容:

两个关于Go语言良好编码风格的参考文档如下:

我还建议您在代码中使用以下工具:

英文:

The two sources of good style in go are these two documents:

I would also recommend to use these tools for your code base:

答案2

得分: 1

对于这个问题,没有具体的指导方针,甚至标准库的包也没有遵循相同的方式。但是作为一个经验法则,你应该:

  • 将导出的全局常量和变量(如错误)放在靠近顶部的位置。
  • 将结构体与它们的方法放在一起,而不是将结构体分组放在一起,然后将它们的方法分开。
  • 将逻辑部分分组在一起(无论是结构体、它们的方法还是包函数(导出的或非导出的))。这样以后将包拆分成多个文件会更容易。这样做也使得阅读更容易,因为你不必在文件中跳来跳去。
  • 最后但同样重要的是:如果你使用godoc从你的包生成文档,并且能够从上到下阅读并理解,那么你的顺序可能是正确的 Go style guideline?

如果有疑问,可以查看一些流行的标准库包,比如https://golang.org/src/net/http/server.go。

其他有用的代码风格指南可以在这里找到:

英文:

There is no specific guideline for this and even stdlib packages does not follow the same way. But as a rule of thumb you should:

  • Put exported, global constants and variables (like errors) near the top.
  • Keep structs together with their methods rather than grouping structs together and then their methods separately.
  • Group logical parts together (whenever structs, their methods, package functions (exported or not)). It will make easier splitting your package into multiple files later on. It makes reading easier as well as you don't have to jump all over the file.
  • Last, but not least: if you generate documentation from your package with godoc and can read it from top to bottom with understanding, then your order is probably correct Go style guideline?

When in doubt, check some popular stdlib packages, like https://golang.org/src/net/http/server.go.

Other useful code style guidelines can be found here:

huangapple
  • 本文由 发表于 2017年6月23日 18:42:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/44719451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定