How do I override variables in go from package ?
For example:
file1.go
package A
import "A/B"
var Arg1 = "Hello"
file2.go
package A/B
var Arg1 = "World"
How can I override arg1 in file1.go if arg1 exist in file2.go?
Are you trying to do something like this, where, for example, a specific location (USA), if present, overrides a general location (World)?
// file A/B.go
package B
var location = "USA"
func Location() string {
return location
}
// file A.go
package A
import "A/B"
var location = "World"
func Location() string {
loc := B.Location()
if len(loc) == 0 {
loc = location
}
return loc
}
// file main.go
package main
import (
"A"
"fmt"
)
func main() {
fmt.Println("Hello,", A.Location())
}
Output:
Hello, USA
If not, please provide a better and specific example of what you are trying to do.
You can't. Packages are self-contained. If package A doesn't export arg1 (lowercase) it is not visible -- and thus not set-able -- for an other package B.
BTW: "package A/B" looks pretty strange to me.
I'm not sure what you mean by "overriding" in this case. (Also let me assume file1.go is 'package a' and file2.go is 'package b')
If you mean to access Arg1
, defined in package "b" inside/from within package "a", then eg.:
// In package "a"
x = Arg1 // references a.Arg1
y = b.Arg1 // references b.Arg1
However, nothing resembling overriding happens here. In package "a" both a's Arg1
and b's Arg1
are accessible as different entities; the later via a mandatory qualifier 'b'.