how to implement macros in Go?

后端 未结 2 1759
暖寄归人
暖寄归人 2021-01-12 10:27

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

相关标签:
2条回答
  • 2021-01-12 11:09

    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
    
    0 讨论(0)
  • 2021-01-12 11:22

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

    0 讨论(0)
提交回复
热议问题