🔧 Three things that can go before a package clause in Go
Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to
This post is an excerpt from my email list, Boldy Go: Daily. Join for more content like this every day.
If you’ve done any Go coding at all, you’ve seen at least one package clause:
package main
And you probably know that it comes at the top of each Go source file.
But did you know there are three other things that may come first? Let's look at all three:
-
Comments, including GoDoc. It's good practice to include a descriptive GoDoc paragraph immediately before the
package
clause (i.e. with no blank lines between). You need only do this in a single file (in case of a multi-file package).
// Package foo Foos all the Bars. package foo
-
Build constraints and other directives (these are treated as comments, but are worth mentioning separately).
//go:build !js package foo
In this example, we tell the compiler to ignore this file when building for a JS target (i.e. WebAssembly or GopherJS).
-
A shebang line (only as the very first line of the file).
#!/usr/local/bin/go run package main
What?!
Didn't know that was possible?
This actually isn't a Go thing at all, it's more a shell thing. But all common Unix/Linux shells will recognize such a line, and interpret it as the name of an interpretor to pass the file to. You really should not ever need this in Go, but some folks have fun writing Go for shell-script types of tasks. If that describes you, this will apply. I included this here mostly for completeness sake, not as an endorsement of this approach. 😉
What if we put all three together, just for fun?
#!/usr/local/bin/go run
// this comment does nothing special. It's not GoDoc, becuase
// there's no package clause or declaration on the next line,
// and it's not a build constraint.
//go:build !js
//go:generate /path/to/utility
// Package main is a utility that does something interesting.
package main
🔧 Thất nghiệp tuổi 35
📈 38.33 Punkte
🔧 Programmierung
📰 Writing Window Functions with the Frame Clause
📈 19.47 Punkte
🔧 AI Nachrichten
🐧 SQL Having Clause
📈 19.47 Punkte
🐧 Linux Tipps
🐧 MySQL INSERT IGNORE Clause
📈 19.47 Punkte
🐧 Linux Tipps
📰 Ärger um den Einsatz der Commons Clause
📈 19.47 Punkte
📰 IT Nachrichten
🐧 The Commons Clause will destroy open source
📈 19.47 Punkte
🐧 Linux Tipps
🔧 Understanding OVER() Clause in SQL
📈 19.47 Punkte
🔧 Programmierung