Go and callbacks

I believe that using channels is preferable over callbacks, is there a way to rewrite this with channels that are more idiomatic or callbacks are used 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
    })
}
+4
source share
1 answer

Using callbacks is very acceptable, especially for this type of server template, it is net/*used everywhere.

However, the channel version may look something like this:

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
    }
}
+4
source

All Articles