Go中channel能夠是隻讀、只寫、同時可讀寫的。spa
//定義只讀的channelcode
read_only := make (<-chan int)blog
//定義只寫的channelit
write_only := make (chan<- int)io
//可同時讀寫編譯
read_write := make (chan int)class
定義只讀和只寫的channel意義不大,通常用於在參數傳遞中,見代碼:import
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方法中的參數對調:channel
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)