Can I import a Golang package based on the OS I'm building for?

Viewed 2935

Say I have a go project that based on which OS, and in some cases which distro, I want to use say a Systemd client package vs an Upstart client package vs a sysv client package vs a launchd client package. Is it possible to selectively import each package so I only import the one I need per OS/distro I'm building for? Or do I have to import each package for each OS/distro?

2 Answers

A build constraint is evaluated as the OR of space-separated options; each option evaluates as the AND of its comma-separated terms; and each term is an alphanumeric word or, preceded by !

Actually, that will change with Go 1.17 (Q3 2021)

//go:build lines

The go command now understands //go:build lines and prefers them over // +build lines.

The new syntax uses boolean expressions, just like Go, and should be less error-prone.

As of this release, the new syntax is fully supported, and all Go files should be updated to have both forms with the same meaning.
To aid in migration, gofmt now automatically synchronizes the two forms.
For more details on the syntax and migration plan, see https://golang.org/design/draft-gobuild.

From the design document:

The core idea of the design is to replace the current // +build lines for build tag selection with new //go:build lines that use more familiar boolean expressions.

For example, the old syntax

// +build linux
// +build 386

would be replaced by the new syntax

//go:build linux && 386
Related