Go language basic directional channel

directional channel

The default channel is bidirectional: make(chan T)

Readable, writable
send data: chan <- data
read data: <- chan
directional, also called one-way channel
read-only: only receive
<- chan T
write only: only send
chan <- T
for passing of parameters

In the function: only read operations, can pass read-only channels

package main

import "fmt"
 func main () {
    /*
    Two-way:
       chan T -->
          chan <- data, write out data, write
          data <- chan, get data, read
   One-way
 : directional       chan <- T,
          only support writing,
       <- chan T,
          read only
     */
 ch1 := make ( chan string ) // bidirectional, readable, writable
 done := make ( chan bool )
     go test1(ch1 , done)
        
    data :=<- ch1 //Block
     fmt.Println( "Sub-goroutine comes:" , data)
    ch1 <- "I'm main.." // blocking
 <-done
    
    fmt.Println("main...over....")
}
//Sub goroutine-->Write data to ch1 channel
 //main goroutine-->Get func test1 from ch1 channel
 (ch1 chan string , done chan bool ) {
   ch1 <- "I'm Xiaoming" // block
    data := <-ch1 // block
    fmt.Println( "main goroutine comes:" , data)

   done <- true
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325893867&siteId=291194637