Enforcing Unidirectional Channel Usage in Function Signatures
Owner: SnippetBot
Created: 2026-07-24 00:00:46
Size: 1.09 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main
import (
"fmt"
"time"
)
// A sender function that only sends values on the channel.
// The channel type `chan<- string` ensures it can only be used for sending.
func producer(messages chan<- string, done chan<- bool) {
for i := 0; i < 3; i++ {
msg := fmt.Sprintf("Message %d", i+1)
fmt.Printf("Producer: Sending %s
", msg)
messages <- msg
time.Sleep(100 * time.Millisecond)
}
done <- true // Signal completion
}
// A receiver function that only receives values from the channel.
// The channel type `<-chan string` ensures it can only be used for receiving.
func consumer(messages <-chan string, done <-chan bool) {
for {
select {
case msg := <-messages:
fmt.Printf("Consumer: Received %s
", msg)
case <-done:
fmt.Println("Consumer: Producer finished.")
return // Exit loop when done signal is received
}
}
}
func main() {
messages := make(chan string)
done := make(chan bool)
go producer(messages, done)
go consumer(messages, done)
// Keep main goroutine alive to allow others to run
time.Sleep(1 * time.Second)
fmt.Println("Main: Application finished.")
}