1

I want to add some code to start of function. like


source code:

func A(){
    do something...
}

final code:

func A(){
    ADDED CODE
    do something...
}

I`m using //go:generate right now,but it will change the source code and should run it every function changed,so I wonder if there any way to do the job in compile time

贺玉琨
  • 29
  • 1
  • Does this answer your question? [How to set package variable using -ldflags -X in Golang build](https://stackoverflow.com/questions/47509272/how-to-set-package-variable-using-ldflags-x-in-golang-build) – The Fool Feb 24 '22 at 08:21
  • The code I want to add is a little complex, so the -X is not applicable to me – 贺玉琨 Feb 24 '22 at 08:35

2 Answers2

0

What about using a function call to add code?

package mypkg

var extra = func() {}

func A() {
  extra()
  // ...do something
}

Then you can include or exclude an extra file to the same package:

package mypkg

func init() {
  extra = func() {
    // ADDED CODE
  }
}

You even could select from one ore more files with alternatives for the extra() function.

Das Jott
  • 996
  • 8
  • 13
-2

[H]ow to generate or change code in compile time?

You have to modify the compiler. (Don't do that.)

Volker
  • 40,468
  • 7
  • 81
  • 87