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.

GoResilience

Code

gosnippet
25 lines
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

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.