I've got a struct in a file that begins with this line:
// +build windows
Therefore it will only be built on Windows. However, the part of the application that initializes everything needs to check if it is running on Windows and if so, create an instance of the struct. I have no idea how to do this without breaking things on other platforms.
For example, if the file contains a function newWindowsSpecificThing()
and I compile on Linux, the function won't exist because it is defined in a file that isn't being compiled. (And, of course, this will produce an error.)
How do I work around this dilemma?
Somewhere you clearly have a function that calls newWindowsSpecificThing()
. That should be in a Windows-specific file. If it were, then it wouldn't matter that it isn't available. The fact that you have something "check if it is running on Windows" suggests a if runtime.GOOS == "windows"
statement somewhere. Rather than have that, move the entire if
into a function that is defined in a Windows-specific file. You'll also need to define that function in a !windows
file, which is fine.
As an example from my code, I have a function:
func Setup() *config {
var cfg *config
// setup portable parts of cfg
return PlatformSpecificSetup(cfg)
}
I then have a file marked // +build windows
that defines PlatformSpecificSetup()
one way, and another marked // +build !windows
that defines it another. I never have to check runtime.GOOS
and I never have to deal with undefined data types. The config
struct itself is defined in those files, so it can have different fields for each platform (as long as they agree enough for Setup()
). If I were being more careful, I could create a struct like:
type config struct {
// independent stuff
plat *platformConfig
}
And then just define platformConfig
in each platform file, but in practice I've found that more trouble than it's worth.