Skip to content

Instantly share code, notes, and snippets.

@humamfauzi
Created October 9, 2022 14:57
Show Gist options
  • Save humamfauzi/359156c5f4b4f21e3b8f2920019e3673 to your computer and use it in GitHub Desktop.
Save humamfauzi/359156c5f4b4f21e3b8f2920019e3673 to your computer and use it in GitHub Desktop.
Distributed task
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println("Hello, 世界")
errChan := make(chan error)
aChan, genFunc1 := ChanFunc(errChan, Example)
bChan, genFunc2 := ChanFunc(errChan, Example)
cChan, genFunc3 := ChanFunc(errChan, Example)
go genFunc1("12")
go genFunc2("13")
go genFunc3("ab")
for i := 0; i < 3; i++ {
if err := <-errChan; err != nil {
panic(err)
}
}
a, b, c := <-aChan, <-bChan, <-cChan
fmt.Println(a, b, c)
}
func Example(input string) (int, error) {
o, err := strconv.Atoi(input)
if err != nil {
return o, err
}
return o, nil
}
func ChanFunc[Input, Output any](errChan chan error, inputFunc func(Input) (Output, error)) (chan Output, func(Input)) {
oChan := make(chan Output, 1)
genFunc := func(input Input) {
o, err := inputFunc(input)
if err != nil {
errChan <- err
return
}
oChan <- o
}
return oChan, genFunc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment