LoginSignup
3
1

More than 3 years have passed since last update.

送信専用channelと受信専用channel

Posted at

宣言方法

goにおけるchannelとは何か、とかは今は省略。
日本語のchannelについての記事を見ていると、
chan<- intを「送信専用」、<-chan intを「受信専用」と書かれているものがいくつも見つかって、混乱したのでメモしておく
(例えば、https://qiita.com/yuki2006/items/3f90e53ce74c6cff1608)
(あるいは、https://qiita.com/marnie_ms4/items/cc2e49d4f11884e16611)

// int型を扱う「送信専用?」チャネル
type s_ch chan<- int

// int型を扱う「受信専用?」チャネル
type r_ch <-chan int

個人的に、「送信専用」なのに矢印がchanへ向いている(受信?)し、「受信専用」なのに矢印がchanの外側に向かっている(送信?)のように見えるから、混乱した

結論から言うと、この違和感は正しいと思う。

英語のチュートリアルページの説明

http://golangtutorials.blogspot.com/2011/06/channels-in-go.html
かなり古い記事だが、これを読むと、上記の受信専用、送信専用の定義は逆転するし、とてもわかりやすくなる。上記のような混乱はまず起きない。


// <-chan intは送信専用 dataを送信するだけのチャネル
ic_send_only := make (<-chan int) //a channel that can only send data - arrow going out is sending
// chan<- intは受信専用 dataを受信するだけのチャネル
ic_recv_only := make (chan<- int) //a channel that can only receive a data - arrow going in is receiving 

https://qiita.com/TsuyoshiUshio@github/items/d94a3d0f934bde6d6aed
この記事でも自分と似たようなモヤモヤが書かれています

3
1
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
3
1