包含连字符的包名称
Package name containing hyphen
我无法理解为什么当我的包中有连字符时我的代码会报错。
例如如果我有一个包名 foo-bar 并且我声明了那个包名
package foo-bar
foo-bar/config.go:1:13: expected ';', found '-'
那为什么 Go 编译器会报错?这是否意味着我们不应该在 go 包名称中使用连字符?
因为有很多 repo 在包名中使用连字符,我是不是做错了什么?
The style of names typical of another language might not be idiomatic in a Go program. Here are two examples of names that might be good style in other languages but do not fit well in Go:
- computeServiceClient
- priority_queue
如果您的包裹地址名称中有-
,您可以将您的包裹名称设置为带下划线。
示例:
打包文件地址:some/where/foo-bar/config.go
package foo_bar
// your codes
我们可以看到from the Go spec包名必须是有效的标识符:
PackageName = identifier .
我们可以进一步read有效标识符定义为:
identifier = letter { letter | unicode_digit } .
所以包名只能包含字母和数字。 -
个字符是不允许的。
我们可以further read作为一种特殊情况,下划线字符(_
)被定义为一个字母,用于 Go 标识符:
The underscore character _ (U+005F) is considered a letter.
因此,如果您愿意,可以将 -
替换为 _
作为您的包裹名称。
但是,请考虑不要这样做,因为它被认为是non-idiomatic。有关 Go 包命名的建议,请阅读 Effective Go on package names, or read The Go Blog's post on Package Names.
部分
虽然没有直接关系,但出于某种原因,在创建项目布局时,我一直在尝试搜索是否有关于 go 模块“路径”部分命名的规则或指南。我发现除了“还有几个lexical restrictions on characters allowed in module paths" in Go Modules Reference。我想我可以在组织目录结构时随意使用连字符。
我无法理解为什么当我的包中有连字符时我的代码会报错。 例如如果我有一个包名 foo-bar 并且我声明了那个包名
package foo-bar
foo-bar/config.go:1:13: expected ';', found '-'
那为什么 Go 编译器会报错?这是否意味着我们不应该在 go 包名称中使用连字符?
因为有很多 repo 在包名中使用连字符,我是不是做错了什么?
The style of names typical of another language might not be idiomatic in a Go program. Here are two examples of names that might be good style in other languages but do not fit well in Go:
- computeServiceClient
- priority_queue
如果您的包裹地址名称中有-
,您可以将您的包裹名称设置为带下划线。
示例:
打包文件地址:some/where/foo-bar/config.go
package foo_bar
// your codes
我们可以看到from the Go spec包名必须是有效的标识符:
PackageName = identifier .
我们可以进一步read有效标识符定义为:
identifier = letter { letter | unicode_digit } .
所以包名只能包含字母和数字。 -
个字符是不允许的。
我们可以further read作为一种特殊情况,下划线字符(_
)被定义为一个字母,用于 Go 标识符:
The underscore character _ (U+005F) is considered a letter.
因此,如果您愿意,可以将 -
替换为 _
作为您的包裹名称。
但是,请考虑不要这样做,因为它被认为是non-idiomatic。有关 Go 包命名的建议,请阅读 Effective Go on package names, or read The Go Blog's post on Package Names.
部分虽然没有直接关系,但出于某种原因,在创建项目布局时,我一直在尝试搜索是否有关于 go 模块“路径”部分命名的规则或指南。我发现除了“还有几个lexical restrictions on characters allowed in module paths" in Go Modules Reference。我想我可以在组织目录结构时随意使用连字符。