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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM