Reputation: 792
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?
Upvotes: 3
Views: 3736
Reputation: 41
You could probably do it using a build flag :
go build -ldflags="-X 'package_path.variable_name=new_value'"
Couple of things to be aware of though :
In order to use ldflags, the value you want to change must exist and be a package level variable of type string. This variable can be either exported or unexported. The value cannot be a const or have its value set by the result of a function call
You'll find all the information needed in this excellent post from DO team
Upvotes: 1
Reputation: 166714
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.
Upvotes: 1
Reputation: 91321
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'.
Upvotes: 3
Reputation: 42431
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.
Upvotes: 1