去和回调

时间:2014-08-08 12:51:28

标签: go

我认为使用频道比回调更受欢迎,有没有办法用更惯用的频道重写这个频道,或者在这里使用回调就好了:

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 个答案:

答案 0 :(得分:4)

使用回调是非常可接受的,特别是对于那种服务器模式,net/*在整个地方使用它。

但是,频道版本可能类似于:

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