Go tip of the week: Futures in Go

Do you miss futures in Go? Did you search for a Go package that implements futures? Look no further! Futures can be trivially modeled in Go using goroutines and channels.

If you haven't heard about futures yet, futures represent the result of an asynchronous computation that may not be ready yet. They act like a proxy for a value that will be available later.

The simplest way to create a future in Go is by using a goroutine and a channel:

Make a channel that will hold the future result:

resultChan := make(chan int)

Launch a goroutine to compute the result asynchronously:

go func() {
    resultChan <- doLongComputation()
}()

Read from the channel later to retrieve the result:

result := <-resultChan

When you try to read from the channel, it will block until the goroutine finishes the computation and sends the result. This basic pattern handles the key aspects of futures - decoupling the result from computation and synchronization.

So in just 3 lines of code, you can implement a simple future in Go using built-in concurrency features. No special packages needed!

More on this: https://appliedgo.net/futures/