A directional channel is a channel that can only send or receive data.
A two-way channel looks like this:
package main
import "fmt"
func main() {
ch1 := make(chan string)
//建立一个chanel 通知一下 在子协程没结束之前 主协程不要结束
done := make(chan bool)
go sendData(ch1, done)
data := <-ch1
fmt.Println("子协程中传来的数据: ", data)
ch1 <- "that is rain"
<-done
fmt.Println("main finished")
}
func sendData(ch1 chan string, done chan bool) {
ch1 <- "this is bill"
data := <-ch1
fmt.Println("主协程传来的数据", data)
//这个表示在子的协程结束的时候 再传递一个 bool 告诉 主协程 子协程已经执行完毕,否则主协程先不要结束
done <- true
}
The result of running is this:
子协程中传来的数据: this is bill
主协程传来的数据 that is rain
main finished
The above is the writing method of the two-way channel. The following is a description of the one-way channel:
package main
import "fmt"
func main() {
//双向chanel
ch1 := make(chan int)
//单向:只能写
//ch2 := make(chan<- int)
////单向:只能读
//ch3 := make(<-chan int)
go writes(ch1)
//go writes(ch2)
data := <-ch1
fmt.Println("the data from writes is : ", data)
}
func writes(ch chan<- int) {
ch <- 100
fmt.Println("writing completed")
}
For the so-called one-way channel, at the beginning of creation, a two-way channel is usually created, but only in the function (for example, the writes here are set to write-only).
Reference: bilibili
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。