Closing Channels Ends Range And Receives

Close a channel after the last send so range loops end naturally and later receives return the zero value with ok false instead of blocking forever.

GoData Integrity

Code

gosnippet
29 lines
package main

import "fmt"

// produce 返回只接收通道:调用方只能收,不能 close 或发送
func produce(items []string) <-chan string {
	out := make(chan string)
	go func() {
		// 最后一个发送之后必须 close,否则接收方 range 永久阻塞
		defer close(out)
		for _, item := range items {
			out <- item
		}
	}()
	return out
}

func main() {
	ch := produce([]string{"lint", "test", "build"})

	// range 在通道 close 且取完剩余元素后自然结束
	for item := range ch {
		fmt.Println("processed:", item)
	}

	// close 后再接收立即返回零值,ok=false 表示通道已耗尽
	value, ok := <-ch
	fmt.Println("after close:", value, ok)
}

What closing a channel does

All the action sits in the functions produce and main — everything else is wiring.

Iteration happens inside for _, item := range items — everything outside it runs once. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.

Watch out for

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Applying it

Entry signature: func produce(items []string) <-chan string

The run emits 2 labeled sections — processed:, after close: — one per step.

The entry point wires produce together — run it once and the whole demo flows.

Statements that matter

func produce(items []string) <-chan string {
	out := make(chan string)
	go func() {
		// 最后一个发送之后必须 close,否则接收方 range 永久阻塞
		defer close(out)
		for _, item := range items {
			out <- item
		}
	}()
	return out
}
for item := range ch {
	fmt.Println("processed:", item)
}
value, ok := <-ch

Interactive Tools for This Topic

FAQ

What does Closing Channels Ends Range And Receives print when run?
Invoke the file as-is — the `processed:`, `after close:` prefixes identify which step printed each line.