Go channel 通道

Go About 631 words

创建 channel

创建一个接收string类型的channel

ch := make(chan string)

关闭 channel

ch := make(chan string)
close(ch)

发送数据

ch := make(chan string)
ch <- "abc"

接收数据

ch := make(chan string)
str := <-ch
println(str)

单向发送

使用chan<-类型表示单向发送

单向发送,只能发送,可以在发送端关闭通道

func Publish(publisher chan<- string) {
    publisher <- "aaa"
    close(publisher)
}

单向接收

使用<-chan类型表示单向接收

不能在单向接收的channel类型中关闭channel

func Receive(receiver <-chan string) {
    str := <-receiver
    println(str)
    //Cannot use 'receiver' (type <-chan string) as the type chan<- Type Must be a bidirectional or send-only channel
    //close(receiver)
}
Views: 293 · Posted: 2023-09-25

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh