Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement macros in Go?

Tags:

macros

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.

like image 372
Pavani siva dath Avatar asked Mar 28 '18 06:03

Pavani siva dath


2 Answers

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.

like image 176
kostix Avatar answered Sep 20 '22 19:09

kostix


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
like image 29
Shiva Kishore Avatar answered Sep 22 '22 19:09

Shiva Kishore