17

I am having some trouble understanding that why my code complains when I have hyphen in package. e.g. if I have a package name foo-bar and I declare that package name

package foo-bar

foo-bar/config.go:1:13: expected ';', found '-'

Then why does the Go compiler complain? Does it mean we should not use hyphens in go package names?

Since there are many repo that has use hyphen in package name, am I doing something wrong?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Aman Chourasiya
  • 1,078
  • 1
  • 10
  • 23
  • 3
    By convention, packages are given lower case, single-word names; there should be no need for underscores or mixedCaps. [Ref](https://golang.org/doc/effective_go.html#package-names) – Kamol Hasan Aug 17 '20 at 07:45
  • "Does it mean we should not use hyphens in go package names?" It doesn't mean you should not, it means you must not. Dead simple. – Volker Aug 17 '20 at 09:28

3 Answers3

42

We can see from the Go spec that a package name must be a valid identifier:

PackageName = identifier .

We can further read that a valid identifier is defined as:

identifier = letter { letter | unicode_digit } .

So package names may contain only letters and digits. - characters are not permitted.

We can further read that as a bit of a special case, the underscore character (_) is defined as a letter, for the purpose of Go identifiers:

The underscore character _ (U+005F) is considered a letter.

So you may substitute - with _ for your package name if you wish.

However, please consider not doing so, as it's considered non-idiomatic. For advice on package naming in Go, please read the section of Effective Go on package names, or read The Go Blog's post on Package Names.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
12

from Go Package Name blog post:

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

If your package address has - in name, your can set your package name with an underline.

Example:

package file address : some/where/foo-bar/config.go

package foo_bar

// your codes
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ttrasn
  • 4,322
  • 4
  • 26
  • 43
0

Though not directly related, for some reason when creating a project layout I keep trying to search whether there are rules or guidelines regarding the naming of the "path" part of go modules. I found little other than "There are also several lexical restrictions on characters allowed in module paths" in Go Modules Reference. I guess I can use hyphens freely when organizing the directory structure.

JYing
  • 21
  • 2