douluokuang7184 2019-04-22 06:23
浏览 3
已采纳

如何在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?

  • 写回答

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 embeds x, so z{}.method() will return x. You can change this to y by embedding the y struct instead of the x one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题