I'm trying to extend a map across packages at 'compile time'. Is this possible?
I have package A
with a predefined map:
package A
var MyMap = map[string]string{"key1": "value", "key2": "value"}
And I would like to extend the map during 'compile time'. This shall be done in another package. E.g. like so (not working code ofc.):
package B
import "A"
A.MyMap.Slice1["key3"] = "value" // extend the map during compile time
Is this somehow possible?
You can't do this "at compile" time. In fact, the composite literal that package A
uses, that also will be constructed and used at runtime. There are no composite literal constants.
Going further, whatever code you write in package B
, if it imports package A
, code of package B
will only run after package A
has been initialized, including the map you posted.
If you want A.MyMap
to have a different value before it can be seen by any other package, you should modify the source of package A
. This could be a generated additional file, which could use a package init()
function, assigning a new value to MyMap
, or adding new values to it.
If you can, you could also modify package A
so that the initialization of MyMap
is moved to a different source file, one that can be generated.