Jamie McCrindle
Jamie McCrindle

Reputation: 9214

Go and Callbacks

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

Upvotes: 7

Views: 4835

Answers (1)

OneOfOne
OneOfOne

Reputation: 99351

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

Upvotes: 7

Related Questions