英文:
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() <- chan *SomeServer {
ch := make(chan *SomeServer)
someServer := &SomeServer{}
go func() {
for i := 0; i < 10; i++ {
ch <- 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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论