有没有办法拦截围棋功能?

我是golang的新手,想知道是否有任何方法可以拦截函数。


例如,如果我有:


func (foo Foo) f1(a int) int {...}

func (foo Foo) f2(a, b int) int {...}

func (foo Foo) f3(a, b, c int) int {...}

我想实现一些日志记录功能,而不是在每个函数中放置前置和后置拦截器:


func (foo Foo) f1(a int) int {

  preCall()

  ...

  postCall()

}


func (foo Foo) f2(a, b int) int {

  preCall()

  ...

  postCall()

}


func (foo Foo) f3(a, b, c int) int {

  preCall()

  ...

  postCall()

}

有没有更好的模式来做到这一点?例如Java中的AOP。


狐的传说
浏览 104回答 2
2回答

蝴蝶不菲

没有办法在AOP意义上拦截/编织代码。但是,您可以使用闭包来解决装饰器模式的函数参数限制package mainimport "fmt"type Foo struct{}func (foo Foo) f1(a int) {    fmt.Printf("f1: %v\n", a)}func (foo Foo) f2(a, b int) {    fmt.Printf("f2: %v, %v\n", a, b)}func (foo Foo) f3(a, b, c int) int {    fmt.Printf("f3: %v, %v, %v\n", a, b, c)    return a + b + c}func Wrap(f func()) {    fmt.Printf("preCall\n")    f()    fmt.Printf("postCall\n")}func main() {    f := Foo{}    var res int    Wrap(func() { f.f1(1) })    Wrap(func() { f.f2(1, 2) })    Wrap(func() { res = f.f3(1, 2, 3) })    fmt.Printf("res of f3: %v\n", res)}

慕尼黑的夜晚无繁华

有没有办法拦截围棋功能?没有。Go不提供这样的东西,因为源代码直接编译为机器代码,Go的运行时没有选择挂接这些东西。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go