Go语言通道函数参数

GolangGolangBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

本实验旨在测试你对在 Go 语言中使用通道作为函数参数的理解。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Golang`")) -.-> go/ConcurrencyGroup(["`Concurrency`"]) go/ConcurrencyGroup -.-> go/channels("`Channels`") subgraph Lab Skills go/channels -.-> lab-15457{{"`Go语言通道函数参数`"}} end

通道方向

本实验要解决的问题是修改给定代码,以确保用作函数参数的通道被指定为仅用于发送或接收值。

  • 具备 Go 语言的基础知识
  • 理解通道及其在 Go 语言中的用法
$ go run channel-directions.go
passed message

以下是完整代码:

// 当使用通道作为函数参数时,你可以
// 指定一个通道是仅用于发送还是接收
// 值。这种特定性提高了程序的类型安全性。

package main

import "fmt"

// 这个 `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, "passed message")
	pong(pings, pongs)
	fmt.Println(<-pongs)
}

总结

在本实验中,你学习了如何指定一个通道是仅用于发送还是接收值,这提高了程序的类型安全性。

您可能感兴趣的其他 Golang 教程