Go和回调函数

huangapple go评论150阅读模式
英文:

Go and Callbacks

问题

我相信使用通道(channels)优于回调(callbacks),有没有一种更符合惯用法的使用通道重写这段代码的方式,或者在这里使用回调是否可以接受:

type SomeServer struct { }

func RunSomeServer(callback func(SomeServer)) {
	someServer := SomeServer{}
	// 进行其他设置
	callback(someServer)
	// 清理工作
}

func TestSomeServer(t *testing.T) {
	// 一些服务器仅在回调的生命周期内存在
	RunSomeServer(func(someServer SomeServer) {
		// 对一些服务器运行一些测试
	})
}
英文:

I believe the use of channels is preferred over callbacks, is there a way to rewrite this with channels that is more idiomatic or is the use of callbacks ok here:

type SomeServer struct { }

func RunSomeServer(callback func(SomeServer)) {
	someServer := SomeServer{}
	// do some other setup
	callback(someServer)
	// tear things down
}

func TestSomeServer(t *testing.T) {
	// some server only exists for the lifetime of the callback
	RunSomeServer(func(someServer SomeServer) {
		// run some tests against some Server
	})
}

答案1

得分: 6

使用回调函数是非常可接受的,特别是对于那种服务器模式,net/* 在很多地方都使用了它。

然而,通道版本可能看起来像这样:

func RunSomeServer() <-chan *SomeServer {
    ch := make(chan *SomeServer)
    someServer := &SomeServer{}
    go func() {
        for i := 0; i < 10; i++ {
            ch <- someServer //确保 someServer 处理并发访问
        }
        close(ch)
        //拆除一些东西
    }()

    return ch
}

func TestSomeServer(t *testing.T) {
    ch := RunSomeServer()
    for ss := range ch {
        _ = ss
        //使用 ss 做一些事情
    }
}
英文:

Using callbacks is very acceptable, specially for that kind of server pattern, net/* uses it all over the place.

However, the channel version could look something like:

func RunSomeServer() &lt;- chan *SomeServer {
	ch := make(chan *SomeServer)
	someServer := &amp;SomeServer{}
	go func() {
		for i := 0; i &lt; 10; i++ {
			ch &lt;- someServer //make sure someServer handles concurrent access
		}
		close(ch)
		//tear things down
	}()

	return ch
}

func TestSomeServer(t *testing.T) {
	ch := RunSomeServer()
	for ss := range ch {
		_ = ss
		//do stuff with ss
	}
}

huangapple
  • 本文由 发表于 2014年8月8日 20:51:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/25203988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定