Created
July 11, 2020 11:07
-
-
Save sudaraka94/b2860038408ba4effc2c2839b39ad228 to your computer and use it in GitHub Desktop.
This is an example implementation of futures in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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