Conditional global variable in Golang

45 views Asked by At

I have a configuration constant.

const connectionIsSerial = false // Or maybe true...

And a type definition:

type connection struct {
    connected bool
    mutex     sync.Mutex
    handler *mb.RTUOverTCPClientHandler // Option A - For TCP handler.
    //handler * mb.RTUClientHandler     // Option B - For serial handler.
}

And a global variable to store the connection:

var conn connection

Both types of handler have similar methods. I want to be able to conditionally define the above type connection at compile time, similarly to what you would do with #ifdef preprocessor directives in C.

The only solution I have found so far is to do something like:

type connection struct {
    connected bool
    mutex     sync.Mutex
    handler   any
}

And then conditionally assert the type every time the handler is called. This is a pain and looks ugly too. I know that Go is very different, but I am sure some elegant solution exists out there... Any advice?

0

There are 0 answers