gpt4 book ai didi

执行和回调

转载 作者:IT王子 更新时间:2023-10-29 00:44:13 26 4
gpt4 key购买 nike

我相信 channel 的使用优于回调,有没有一种方法可以用更惯用的 channel 重写它,或者在这里可以使用回调:

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
})
}

最佳答案

使用回调是可以接受的,特别是对于那种服务器模式,net/* 到处都在使用它。

但是, channel 版本可能类似于:

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
}
}

关于执行和回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25203988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com