Skip to content

Instantly share code, notes, and snippets.

@sudaraka94
Created July 11, 2020 11:07
Show Gist options
  • Save sudaraka94/b2860038408ba4effc2c2839b39ad228 to your computer and use it in GitHub Desktop.
Save sudaraka94/b2860038408ba4effc2c2839b39ad228 to your computer and use it in GitHub Desktop.
This is an example implementation of futures in Go
package main
import (
"fmt"
"time"
)
var users = map[int]string{
1: "Rob",
2: "Ken",
}
// This function will return a buffered channel which will later resolve into the response
func NameById(id int) <-chan string {
c := make(chan string, 1)
go func() {
name, ok := users[id]
time.Sleep(10000 * time.Millisecond)
if !ok {
close(c)
return
}
c <- name
}()
return c
}
func main() {
start := time.Now()
a := NameById(1)
b := NameById(2)
fmt.Println(<-a, <-b)
fmt.Println(time.Since(start))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment