Empty Struct Channels Signal Without Data
Signal completion with chan struct{} channels that carry zero bytes, broadcast to every waiter with close, and use map[string]struct{} as a free set.
Code
package main
import "fmt"
// struct{} 占 0 字节:信号通道只表达「事件已发生」,不携带任何数据
type job struct {
done chan struct{}
}
func (j *job) run() {
fmt.Println("work started")
close(j.done) // 关闭即广播信号,所有等待者同时放行
}
func (j *job) wait() { <-j.done }
func main() {
// map[string]struct{}:零开销集合,比 map[string]bool 省内存
deny := map[string]struct{}{"root": {}, "admin": {}}
for _, user := range []string{"root", "alice"} {
if _, blocked := deny[user]; blocked {
fmt.Println(user, "blocked")
} else {
fmt.Println(user, "allowed")
}
}
j := &job{done: make(chan struct{})}
go j.run()
j.wait() // 阻塞直到信号到达
fmt.Println("signalled by chan struct{}")
}What the code does
Empty Struct Channels Signal Without Data comes down to the functions run, wait and main.
Repetition is confined to for _, user := range []string{"root", "alice"} — the rest of the file is straight-line.
Using it
Signature: func (j *job) run()
The demo output is labeled (work started, signalled by chan struct), so every printed line can be tied to the operation behind it.
The sequence run and wait lives in main; running the file triggers it.
Key statements
func (j *job) wait() { <-j.done }
for _, user := range []string{"root", "alice"} {
if _, blocked := deny[user]; blocked {
fmt.Println(user, "blocked")
} else {
fmt.Println(user, "allowed")
}
}
j := &job{done: make(chan struct{})}
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 Empty Struct Channels Signal Without Data print when run?
- Running the file directly is enough — expect labeled output lines such as `work started`, `signalled by chan struct`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.