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?
1条回答 默认 最新
- douzhang6646 2019-04-23 03:08关注
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 embedsx
, soz{}.method()
will returnx
. You can change this toy
by embedding they
struct instead of thex
one.本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 宇视监控服务器无法登录
- ¥15 PADS Logic 原理图
- ¥15 PADS Logic 图标
- ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
- ¥15 DruidDataSource一直closing
- ¥20 气象站点数据求取中~
- ¥15 如何获取APP内弹出的网址链接
- ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
- ¥50 STM32单片机传感器读取错误
- ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据