Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go and Callbacks

Tags:

go

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
    })
}
like image 881
Jamie McCrindle Avatar asked Aug 08 '14 12:08

Jamie McCrindle


1 Answers

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
    }
}
like image 133
OneOfOne Avatar answered Oct 17 '22 18:10

OneOfOne