I've project done in C++ where I used #define
macros to give a name of the project, which I used in several places, I don't change this name often but sometimes I may need to change this, then I change this macro and rebuild my code. Now I'm converting this code to Go. Can someone suggest me how to implement this in Go? I'm not interested in using global variables for this purpose because I've many such macros and I doubt this cause my project to occupy more cpu and effect the performance.
Luckily, Go does not support macros.
There are two venues in Go to implement what is done using macros in other programming languages:
It appears, the latter is what you're after.
Unfortunately, the help on this feature is nearly undiscoverable on itself, but it explained in the output of
$ go tool link -help
To cite the relevant bit from it:
-X definition
add string value
definition
of the formimportpath.name=value
So you roll like this:
In any package, where it is convenient, you define a string constant the value of which you'd like to change at build time.
Let's say, you define constant Bar
in package foo
.
You pass a special flag to the go build
or go install
invocation for the linking phase at compile time:
$ go install -ldflags='-X foo.Bar="my super cool string"'
As the result, the produced binary will have the constant foo.Bar
set to the value "my super cool string" in its "read-only data" segment,
and that value will be used by the program's code.
See also the go help build
output about the -ldflags
option.
Go doesn't support Macros
.
but you can use a constants inside a package and refer it where ever you need.
package constant
// constants.go file
const (
ProjectName = "My Project"
Title = "Awesome Title"
)
and in your program
package main
import "<path to project>/constant" // replace the path to project with your path from GOPATH
func main() {
fmt.Println(constant.ProjectName)
}
The project structure would be
project
|- constant
| |- constants.go
|-main.go
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With