###第三弾?###
前回のやつはこれ
Goroutineを触った。
今回はタイトル通りチャネルを触っていこうと思う
###channelとは###
並列処理を行った結果を呼び出し先の関数に返すことが出来る。
前回のモノで戻り値を返そうとするとエラーが起きる
###コード###
package main
import "fmt"
func channel(s []int,c chan int){
sum:=0
for i:=0;i<5;i++ {
sum += s[i]
}
c <- sum
}
func main(){
s := []int{1,2,3,4,5}
c := make(chan int)
go channel(s,c)
r := <-c
fmt.Println(r)
}
####解説####
#####func main()#####
- 1~5の数字の入ったスライスを作りこれをsで宣言する
- そしてmakeでchan intで戻り値の値を設定しチャネルとしてcを宣言する
- そして並列処理のためにgoを記入し、引数にスライスとチャネルを入れる
- Go to channel
- そしてchannelからcが送られてきたのでrで受け取る。
#####func channel()#####
- 並列処理によりスレッドぐ作られ、この関数がスタートする
- 引数のスライスを足していき結果をcのチャネルに送信する。
- その時の記号は <- である。
###最後に###
解説が見にくくなってしまった許してください。
次回はBuffer channelでーす。