Hacker News new | ask | show | jobs
by xigoi 1465 days ago
> if I name my source file i_love_linux.go, it won’t get compiled on my Mac

What the fuck?

5 comments

There some file name conventions in place in Go [1]. Files ending in *_test.go are going to be run dufing `go test ` invocation, but not compiled during production build run. In general, last parts of file name reflect "tags", or a platform that this file should be built for. So, in the case of *_linux.go file will only be compiled when it targeted linux platform. Allows to have a file say file_windows_amd64.go and file_linux.go that have functions with same signature, but only one will be picked up for a target platform. Sort of like #ifdef , but at file-name level.

There is a way to specify what file is actually targeting inside the file, through //go: "pragmas" too

[1] https://stackoverflow.com/questions/25161774/what-are-conven...

Others already explained why.

Now a bit more background, this goes back to C and C++, and is considered a best practice to name translation units as name_os_arch or similar pattern, with the header file being only name, instead of #ifdef spaghetti.

This is actually one of the few things I think Go did right.

Explanation from a previous discussion - https://news.ycombinator.com/item?id=16414435

...seriously wtf

In 5 years of writing to code this has never prevented me from naming a file what I wanted to name it. I enforced conventions are nice, when I need to look at what’s different between platforms I can very quickly do so in any large repo.
Yeah, "If I do <some obscure thing> in <chose any language>, and it doesn't work how I like, I don't think it's good"
Naming a file is an obscure thing?
__main__.py? PRN? index.html? "This filename does something special" is hardly a situation unique to Go.
__main__.py clearly stands out with its underscores. index.html is a historical accident. And they're both just single files, not a glob.
Searching around a few blogs mention _linux.go files are only compiled on Linux. But I see nothing in the official documentation, will at least in my quick searches.

It will catch someone out who uses BSD as an acronym for something in their domain model (Bulk Sales Discount?) then xyz_bsd.go doesn't compile.

https://pkg.go.dev/cmd/go#hdr-Build_constraints

  If a file's name, after stripping the extension and a possible _test suffix, matches any of the following patterns:

  *_GOOS
  *_GOARCH
  \*_GOOS_GOARCH
  (example: source_windows_amd64.go) where GOOS and GOARCH represent any known operating system and architecture values respectively, then the file is considered to have an implicit build constraint requiring those terms (in addition to any explicit constraints in the file).
Idiomatically in Go that file would be named `xyz-bsd.go`. All special filename behavior is triggered by `_suffix`.