如何在golang中的F2()之前调用函数F1()

I have a function F2() already in production. F2() is getting called from many other places. I don't want to touch F2() or don't want to touch all the places from where F2 is getting called. How do I call another method F1() just before F2() is called?

It sounds like you want to monkey patch Go code.

There is no real way to do this in Go. Yes, there's github.com/bouk/monkey, but even the author doesn't recommend using it.

You'll either have to:

  • Change your F2().
  • Change the callers of F2().
  • Add an F3() which calls F1() and F2(), or do some other refactor which allows you to do what you want.

There are some ways to change the code that's being run without changing the actual code or callers. This is pretty much what interfaces are for, but you can also do something similar with struct embedding:

type (
    x struct{}
    y struct{}
    z struct{ x }
)

func (_ x) method() string { return "x" }
func (_ y) method() string { return "y" }

The z struct embeds x, so z{}.method() will return x. You can change this to y by embedding the y struct instead of the x one.