1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goといえばチャネルでしょ!!! 第3弾

Posted at

###第三弾?###
前回のやつはこれ
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でーす。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?