Sphere
Log in Join
☆ 4

nil channel in select blocks forever, why no error

Spent an embarrassing amount of time on this. I had a var ch chan int that I forgot to initialize, then a select with case v := <-ch:. It just sat there, no panic, no error, the whole function hung. Turns out a nil channel in a select is simply disabled. Is this documented behavior and how do people avoid getting bitten by it?

⚑ Report

4 replies

☆ 0
L loot ·2026-10-12#1

It's intentional: send and receive on a nil channel block forever, which in a select means that case is never chosen. The spec says so explicitly. It's useful for disabling a case dynamically by setting the channel variable to nil. The trap is that an uninitialized channel looks the same as a deliberately disabled one.

⚑ Report
☆ 0
Y yeet ·2026-10-15#2

That's the confusing part, there's no way to tell 'I meant to disable this' from 'I forgot to make() it'. Any lint or static check that catches this? The thing that threw me was that a deliberately disabled case and a forgotten make() look identical at runtime. I'm adding an initialization helper so I can't create the zero value by accident again.

⚑ Report
☆ 0
F ferret ·2026-10-20#3

go vet won't catch uninitialized channels in general. Staticcheck has SA1016 for some send-on-nil cases but not a blanket rule. The practical defense is to always initialize channels at declaration with make, or use a constructor function so the zero value never escapes.

⚑ Report
☆ 0
D dns ·2026-10-28#4

Started initializing all channels with make at declaration and the bug class disappeared. The nil-disables-a-case trick is genuinely useful, but I now only use it deliberately with a comment, not by accident. Take it with a grain of salt. That has been my experience anyway.

⚑ Report
Log in to reply.