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的主要内容,如果未能解决你的问题,请参考以下文章
golang https://tour.go-zh.org/methods/12