溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Golang單方向的channel

發(fā)布時(shí)間:2020-07-08 09:32:09 來源:網(wǎng)絡(luò) 閱讀:774 作者:ck_god 欄目:編程語言

默認(rèn)情況下,通道是雙向的,也就是,既可以往里面發(fā)送數(shù)據(jù)也可以同里面接收數(shù)據(jù)。

 

但是,我們經(jīng)常見一個(gè)通道作為參數(shù)進(jìn)行傳遞而值希望對方是單向使用的,要么只讓它發(fā)送數(shù)據(jù),要么只讓它接收數(shù)據(jù),這時(shí)候我們可以指定通道的方向。

 

單向channel變量的聲明非常簡單,如下:

var ch2 chan int       // ch2是一個(gè)正常的channel,不是單向的

var ch3 chan<- float64 // ch3是單向channel,只用于寫float64數(shù)據(jù)

var ch4 <-chan int     // ch4是單向channel,只用于讀取int數(shù)據(jù)

 

chan<- 表示數(shù)據(jù)進(jìn)入管道,要把數(shù)據(jù)寫進(jìn)管道,對于調(diào)用者就是輸出。

<-chan 表示數(shù)據(jù)從管道出來,對于調(diào)用者就是得到管道的數(shù)據(jù),當(dāng)然就是輸入。

 

可以將 channel 隱式轉(zhuǎn)換為單向隊(duì)列,只收或只發(fā),不能將單向 channel 轉(zhuǎn)換為普通 channel

    c := make(chan int, 3)

    var send chan<- int = c // send-only

    var recv <-chan int = c // receive-only

    send <- 1

    //<-send //invalid operation: <-send (receive from send-only type chan<- int)

    <-recv

    //recv <- 2 //invalid operation: recv <- 2 (send to receive-only type <-chan int)

 

    //不能將單向 channel 轉(zhuǎn)換為普通 channel

    d1 := (chan int)(send) //cannot convert send (type chan<- int) to type chan int

    d2 := (chan int)(recv) //cannot convert recv (type <-chan int) to type chan int

 

示例代碼:

//   chan<- //只寫

func counter(out chan<- int) {

    defer close(out)

    for i := 0; i < 5; i++ {

        out <- i //如果對方不讀 會阻塞

    }

}

 

//   <-chan //只讀

func printer(in <-chan int) {

    for num := range in {

        fmt.Println(num)

    }

}

 

func main() {

    c := make(chan int) //   chan   //讀寫

 

    go counter(c) //生產(chǎn)者

    printer(c)    //消費(fèi)者

 

    fmt.Println("done")

}

 


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI