最佳答案
spec 中标识符名称中的前导下划线没有定义特殊含义:
Identifiers
Identifiers name program entities such as variables and types. An identifier is a sequence of one or more letters and digits. The first character in an identifier must be a letter.
identifier = letter { letter | unicode_digit } .
a _x9 ThisVariableIsExported αβ
您的示例是从 mockgen.go 生成的代码.
在您链接的包中,您会看到如下内容:
// Recorder for MockTracker (not exported)
type _MockTrackerRecorder struct {
mock *MockTracker
}
mockgen 包中的 sanitize 函数在包名称前添加了一个下划线,它似乎以其他方式用于一致性并确保标识符名称保持私有(private)(即不导出,因为它们以大写字母开头)。但这不是 Go 规范中定义的东西。
// sanitize cleans up a string to make a suitable package name.
func sanitize(s string) string {
t := ""
for _, r := range s {
if t == "" {
if unicode.IsLetter(r) || r == '_' {
t += string(r)
continue
}
} else {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
t += string(r)
continue
}
}
t += "_"
}
if t == "_" {
t = "x"
}
return t
}
关于go - 何时在 Go 变量名中使用前导下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29891677/