【Golang】ゴルーチン⑥関数から関数に値を渡して処理
Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。
package main
// fan-out fan-in
//funcの結果をfuncに渡し、最後に結果をmainに持っていく。
//処理を分けたい時など。func → func でデータを渡す。
import (
"fmt"
)
//15回まわす
func producer(first chan int) {
defer close(first)
for i := 0; i < 15; i++ {
first <- i
}
}
//first,secondを引数
//(first <-chan int受信, second chan<- int送信) で明示的にしていると分かりやすい。
func multi3(first <-chan int, second chan<- int) {
defer close(second)
for i := range first {
//3倍して、チャネルに追加
second <- i * 3
}
}
func multi5(second <-chan int, third chan<- int) {
defer close(third)
for i := range second {
third <- i * 5
}
}
func main() {
first := make(chan int)
second := make(chan int)
third := make(chan int)
go producer(first)
//3倍
go multi3(first, second)
//5倍
go multi5(second, third)
//therdをforで回す
//Producer > multi3 > multi5の順で値が渡される
for result := range third {
fmt.Println(result)
}
}