Detail Golang's recommended naming conventions
- 2020-06-19 10:32:35
- OfStack
Golang recommended naming conventions
It's rare to find a list of common naming conventions, or it may be the result of my ignorance. As a two-year developer of golang, I've compiled a list of common naming conventions based on well-known projects such as moby and kubernetess. Naming conventions make code easier to read and less prone to errors.
If there are different opinions welcome ridicule, discussion. The project address
File naming convention
Since files are not related to packages, and windows case is avoided, the recommended specification is as follows: file names should be in lower case, different words should be separated by underscores, and names should be as recognizable as possible
Constant naming specification
Examples of constants named camelcase are shown below
const todayNews = "Hello"
// If you exceed 1 The constants should be organized in parentheses
const (
systemName = "What"
sysVal = "dasdsada"
)
Variable naming convention
As with constant name 1, variables should also be named as humps, but try not to be associated with or begin with package name 1
var x string
x := new(string)
Function naming convention
Due to the special nature of Golang (which controls the visibility of functions with case), the following principles should be followed with the exception of special performance and unit test functions
Use the hump name Use lowercase functions if you do not need access outside the package Use uppercase function names if you need to expose them for out-of-package accessA typical function naming method is as follows:
// annotation 1 The law USES a double slash, Methods of object exposure
func (*fileDao) AddFile(file *model.File) bool {
result := db.NewRecord(*file)
if result {
db.Create(file)
}
return result
}
// The functions that do not need to be accessed outside the package are as follows
func removeCommaAndQuote(content string) string {
re, _ := regexp.Compile("[\\`\\,]+")
return strings.TrimSpace(re.ReplaceAllString(content, ""))
}
Interface naming specification
Interface naming also follows the camel case naming pattern. type alias can be used to define type starting with uppercase for out-of-package access
type helloWorld interface {
func Hello();
}
type SayHello helloWorld
Struct naming convention
Similar to interface naming conventions
receiver naming convention
receiver name should be kept as close as possible to avoid this, super, and other languages. Some semantic keywords are as follows
type A struct{}
func (a *A) methodA() {
}
func (a *A) methodB() {
a.methodA()
}
Annotation specifications
Comment should be 1 law using double slash
other
Formatting, using tab instead of Spaces, is compatible with go fmt