何时在 Go 变量名中使用前导下划线
When to use leading underscore in variable names in Go
变量名前导_
有什么特殊用途吗?
示例:
func (_m *MockTracker)...
来自 here。
在命名约定中似乎没有关于变量名中的_的内容。
来自这里:effective go
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 函数在包名称前添加了一个下划线,它似乎以其他方式用于一致性并确保标识符名称保持私有(即不导出,因为它们以大写字母开头)。但这不是 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
}
变量名前导_
有什么特殊用途吗?
示例:
func (_m *MockTracker)...
来自 here。
在命名约定中似乎没有关于变量名中的_的内容。 来自这里:effective go
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 函数在包名称前添加了一个下划线,它似乎以其他方式用于一致性并确保标识符名称保持私有(即不导出,因为它们以大写字母开头)。但这不是 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
}