Last active
January 25, 2024 23:07
-
-
Save Micrified/104c5fe39bb70bf39414f24c8fc7c2d2 to your computer and use it in GitHub Desktop.
Go concurrency basic example
This file contains hidden or 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" | |
// Take a variadic list of integers, and launch a goroutine which will block trying to send them on channel 'out' | |
// Return this channel as a receive-only channel | |
func gen(ns ...int) <-chan int { | |
out := make(chan int) // Create a bidirectional channel | |
go func() { | |
for _, n := range ns { | |
out <- n | |
} | |
close(out) | |
}() | |
return out // Demoted to unidirectional receive-only | |
} | |
// Create a channel and write the square of the incoming channel elements to it. The incoming receive-only channel is read | |
// by a launched goroutine, which also writes to the output channel. Let the go routine block waiting for input | |
// and return the output channel (for consumption by the caller) | |
func sq(in <-chan int) <-chan int { | |
out := make(chan int) // Create a bidirection channel | |
go func() { | |
for n := range in { // Note: You don't do for _, n because it's not a slice | |
out <- n * n | |
} | |
close(out) | |
}() | |
return out | |
} | |
// Set up the pipelines | |
func main() { | |
for n := range sq(gen(2,3)) { | |
fmt.Println(n) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment