关于go:Go-快速入门指南-通道方向

2次阅读

共计 732 个字符,预计需要花费 2 分钟才能阅读完成。

概述

通道的方向分为 发送 接管。默认状况下,通道是双向的 (同时发送和接管),然而能够通过标识符指明通道为单向 (只读或只写)。

语法规定

可读写通道 (同时反对发送和接管)

变量 := make(chan 数据类型)
# 例子
ch := make(chan string)

只读通道 (只反对接管)

变量 := make(<-chan 数据类型)
# 例子
ch := make(<-chan string)

只写通道 (只反对发送)

变量 := make(chan<- 数据类型)
# 例子
ch := make(chan<- string)

类型转换

双向通道能够转换为单向通道,然而单向通道无奈转换为双向通道。

例子

package main

// 参数是一个写入通道
func ping(pings chan<- string) {
    //<-pings                    // 谬误: pings 通道只能写入
    pings <- "hello world"
}

func pong(pings <-chan string, pongs chan<- string) {
    //pings <- "hello world"    // 谬误: pings 通道只能读取
    //<-pongs                     // 谬误: pongs 通道只能写入

    msg := <-pings
    pongs <- msg
}

func main() {pings := make(chan string)
    pongs := make(chan string)
    done := make(chan bool)

    go ping(pings)
    go pong(pings, pongs)

    go func() {
        msg := <-pongs
        println(msg)
        done <- true
    }()

    <-done

    close(pings)
    close(pongs)
    close(done)
}

// $ go run main.go
// 输入如下
/**
  hello world
*/

分割我

正文完
 0