当使用通道作为函数的参数时,你可以指定这个通道是不是只用来发送或者接收值。这个特性提升了程序的类型安全性。

Example:

package main

import "fmt"

// <-chan 发送数据
// chan<- 接收数据

//ping 函数定义了一个只允许发送数据的通道。尝试使用这个通道来接收数据将会得到一个编译时错误。
func ping(pings chan<- string, msg string){
    pings<- msg
}

//pong 函数允许通道(pings)来接收数据,另一通道(pongs)来发送数据。
func pong(pings <-chan string, pongs chan<- string){
    msg := <-pings
    pongs <-msg
}

func main(){
    pings := make(chan string, 1)
    pongs := make(chan string, 1)
    ping(pings, "ping messages.")
    pong(pings, pongs)

    fmt.Println(<-pongs)
}

Result:

$ go run example.go
ping messages.

 

坐标: 上一个例子    下一个例子

 

相关文章:

  • 2021-08-21
  • 2021-07-06
  • 2021-06-11
  • 2021-09-06
  • 2021-09-09
  • 2022-02-02
  • 2021-12-19
  • 2021-07-15
猜你喜欢
  • 2021-07-09
  • 2021-12-07
  • 2021-09-19
  • 2021-11-02
  • 2021-08-01
  • 2021-09-05
  • 2021-06-01
相关资源
相似解决方案