天天看點

Go 隻讀/隻寫channel

Go中channel可以是隻讀、隻寫、同時可讀寫的。

//定義隻讀的channel

read_only := make (<-chan int)

//定義隻寫的channel

write_only := make (chan<- int)

//可同時讀寫

read_write := make (chan int)

定義隻讀和隻寫的channel意義不大,一般用于在參數傳遞中,見代碼:

package main

import (
    "fmt"
    "time"
)

func main() {
    c := make(chan int)
    go send(c)
    go recv(c)
    time.Sleep(3 * time.Second)
}
//隻能向chan裡寫資料
func send(c chan<- int) {
    for i := 0; i < 10; i++ {
        c <- i
    }
}
//隻能取channel中的資料
func recv(c <-chan int) {
    for i := range c {
        fmt.Println(i)
    }
}      

如果将上面send方法和recv方法中的參數對調:

func send(c <-chanint) {

func recv(c chan<- int) {

編譯就會報錯:

./channel.go:18: invalid operation: c <- i (send to receive-only type <-chan int)

./channel.go:24: invalid operation: range c (receive from send-only type chan<- int)

-------------------------------------

歡迎關注微信公衆号

golang_everyday 每日Go語言,每日推出一篇學習文章,歡迎閱讀。

掃碼關注更友善