go tour --Channels 涓?Buffered Channels

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go tour --Channels 涓?Buffered Channels相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/%e5%85%b3%e9%97%ad' title='鍏抽棴'>鍏抽棴   and   send   rom   闃诲   鎺ユ敹   from   

鏃犵紦鍐查€氶亾(闃诲閫氶亾) 鍐欏叆鍚庣珛鍗抽樆濉烇紝闇€瑕佸彟涓€涓崗绋嬭鍙栭€氶亾鐨勬暟鎹悗锛屾墠鑳界户缁墽琛屻€?/p>

閫氶亾鎿嶄綔绗?/p>

ch <- v    // Send v to channel ch.
v := <-ch  // Receive from ch, and
           // assign value to v.

鏃犵紦鍐查€氶亾

ch := make(chan int)

鏈夌紦鍐查€氶亾

ch := make(chan int, 100)

鍙戦€佹柟鍙互鍏抽棴閫氶亾浠ユ寚绀轰笉鍐嶅彂閫佸€?/p>

close(c)

鎺ユ敹鏂瑰彲浠ヤ互绗簩涓繑鍥炲€肩‘璁ら€氶亾鏄惁鍏抽棴

v, ok := <-ch

寰幆閲嶅浠庨€氶亾鎺ユ敹鍊硷紝鐩村埌閫氶亾鍏抽棴銆?/p>

 for i := range c

channel 涓嶅儚鏂囦欢;浣犻€氬父涓嶉渶瑕佸叧闂畠浠€傚彧鏈夊綋鎺ユ敹鑰呭繀椤昏鍛婄煡娌℃湁鏇村鐨勫€兼椂锛屽叧闂槸蹇呰鐨勶紝渚嬪缁堟涓€涓?code>range 寰幆銆?/p>

package main

import (
	"fmt"
)

func fibonacci(n int, c chan int) {
	x, y := 0, 1
	for i := 0; i < n; i++ {
		c <- x
		x, y = y, x+y
	}
	close(c)
}

func main() {
	c := make(chan int, 10)
	go fibonacci(cap(c), c)
	for i := range c {
		fmt.Println(i)
	}
}

以上是关于go tour --Channels 涓?Buffered Channels的主要内容,如果未能解决你的问题,请参考以下文章

Go tour

golang https://tour.go-zh.org/methods/12

golang https://tour.go-zh.org/moretypes/20

A Tour of Go: Basics 1

A Tour of Go: Basics 2

A Tour of Go: Basics 3