54
40

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.

チャネルに対するcapとlenについて #golang

Posted at

チャネルの容量

 Go言語のチャネルには容量というものが指定できます.通常,チャネルを作成するには,組込み関数のmakeを使いますが,その第2引数で容量を渡すことができます.第2引数を省略した場合は,容量0のチャネルとなります.

// 容量0
ch1 := make(chan int)
// 容量10
ch2 := make(chan int, 10)

 チャネルの容量は中に保持しておけるバッファのサイズを指しており,バッファがいっぱいになるとチャネルの送信はブロックされます.また,バッファ内に値がない場合は,チャネルからの受信はブロックされます.

ch := make(chan int, 1)
ch <- 100 // ブロックしない
ch <- 200 // ブロックする

capとlen

 チャネルに対して,組込み関数のcapを呼び出すと,チャネルの容量を取得することができます.

Go Playgroundで実行

ch1 := make(chan int, 10)
// 10
fmt.Println(cap(ch1))

ch2 := make(chan int)
// 0
fmt.Println(cap(ch2))

 また,組込み関数のlenを呼び出すとバッファ内にある値の数を取得することができます.

Go Playgroundで実行

ch := make(chan struct{}, 10)
ch <- struct{}{}
// cap: 10 len: 1
fmt.Println("cap:", cap(ch), "len:", len(ch))
<-ch
// cap: 10 len: 0
fmt.Println("cap:", cap(ch), "len:", len(ch))
54
40
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
54
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?