Proper way to choose func at runtime for different operating systems

go

Solution

You could create files with following pattern: `<pkgname>_<osname>.go`

For example:

- your_package_linux.go

- your_package_darwin.go

- your_package_windows.go

Each file could contain function definition for concrete os, in your case it is `func setStartupProcessLaunch()`.

You could see how it is implemented in standard os/signal package for example.

Problem

I really like the cross-compile/platform ease for many tasks that I can get with GO. I have a question regarding, I guess, the equivalent of a #ifdef / #else type of construct for executing/compiling a function based upon the operating system. Here's the scenario - let's say I have a function that inserts information into the OS's control structures to launch a process at the next time the user starts up their system. On Windows I would update the 'RUN/RUNONCE' registry entry for the user, on MAC there would be a plist entry, etc. In essence, I'd like to be able to write someone analogous to this (or have overloaded OS specific functions): ``` func setStartupProcessLaunch () { if [OS is Windows] { updateRegistry(){} } else if [OS is Darwin] { updatePlist(){} } else if [OS is Linux] { doLinuxthing() {} } } ``` Given the static compilation, any of the routines that aren't called would be flagged as a compilation error. So ideally, I'd like to surround my 'doSpecificOS()' functions in #ifdef WINDOWS, #ifdef MAC type of blocks -- what's the proper way to accomplish this? My hope is that I don't need to create several project trees of the same program for each OS platform.

Original source