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 sometim
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
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
.
At build time you pass to the go build
or go install
invocation
a special flag for the linking phase:
$ 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.