What are conventions for filenames in Go?
I could find the conventions for naming packages in Go: no underscore between words, everything lowercase.
Does this convention apply to the filenames too?
Do you also put one struct in one file as if you did for a java class and then name the file after the struct?
Currently, if I have a struct WebServer, I put it in a file web_server.go.
There's a few guidelines to follow.
- File names that begin with "." or "_" are ignored by the go tool
- Files with the suffix
_test.go
are only compiled and run by thego test
tool. - Files with os and architecture specific suffixes automatically follow those same constraints, e.g.
name_linux.go
will only build on linux,name_amd64.go
will only build on amd64. This is the same as having a//+build amd64
line at the top of the file
See the go
docs for more details: https://pkg.go.dev/cmd/go
In addition to the answer provided by JimB, regular file names are lower case, short, and without any sort of underscore or space. Generally, file names follow the same convention as package names. See the Package Names section of Effective Go.
See the strconv package for a good example.
Go is quite liberal in terms of how you organise your code within a package, usually it's whatever improves readability and understanding of your code. The best way to learn how this is done is to study the masters, i.e. have a browse though the standard library:
http://golang.org/src/pkg/
There are 2 rules I can think of however. When specifying code to be compiled for different platforms, you use the platform name as a suffix:
mypkg_linux.go // only builds on linux systems
mypkg_windows_amd64.go // only builds on windows 64bit platforms
Also if you have a file called server.go
, the tests for that file would be in server_test.go
.
Usually underscore in filenames are used to assign platform/arch-only code, for example:
➜ cd $GOROOT/src/pkg/math/
➜ ls sqrt*s
sqrt_386.s sqrt_amd64p32.s sqrt_amd64.s sqrt_arm.s
sqrt_386.s
will only be read by the compiler on 32bit processors, sqrt_amd64.s
on amd64, etc..
It can be any of the valid values of GOOS
and/or GOARCH
(ref.
file_windows_amd64.go
will be only compiled on win64.