Directional Channels With Send-Only And Receive-Only Types
Give producer and consumer functions send-only or receive-only channel parameters so misuse of a pipeline stage fails at compile time, not in production.
Code
package main
import "fmt"
// 只发送(send-only):参数类型 chan<- 禁止接收,close 是发送方的职责
func produce(out chan<- int, items []int) {
for _, v := range items {
out <- v
}
close(out)
}
// 只接收(receive-only):参数类型 <-chan 禁止发送,也不能 close
func consume(in <-chan int) {
for v := range in {
fmt.Println("got:", v)
}
}
func main() {
jobs := make(chan int) // 双向 channel
go produce(jobs, []int{2, 4, 6})
// 双向 directional 类型可隐式收窄为单向,反向转换则编译报错
consume(jobs)
}What the code does
Directional Channels With Send-Only And Receive-Only Types reduces to the functions produce, consume and main.
The cycling part of this snippet is for _, v := range items. A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly.
What to watch for
- Everything it calls is documented as part of the language core.
Applying it
Entry signature: func produce(out chan<- int, items []int)
The run emits 1 labeled section — got: — one per step.
main is the driver: it invokes produce and consume before returning.
Statements that decide the outcome
func produce(out chan<- int, items []int) {
for _, v := range items {
out <- v
}
close(out)
}
func consume(in <-chan int) {
for v := range in {
fmt.Println("got:", v)
}
}
func main() {
jobs := make(chan int) // 双向 channel
go produce(jobs, []int{2, 4, 6})
// 双向 directional 类型可隐式收窄为单向,反向转换则编译报错
consume(jobs)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Directional Channels With Send-Only And Receive-Only Types print when run?
- No setup needed: run the file and look for labeled lines like `got:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.