简体   繁体   中英

how to implement macros in Go?

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:

  • "Meta-programming" is done using code generation .
  • "Magic variables/constants" are implemented using "symbol substitutions" at link time.

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 form importpath.name=value

So you roll like this:

  1. 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 .

  2. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM