Last active
May 2, 2025 13:43
-
-
Save nelsonr/040a2d89b32fc7b767dbc443b78f8f28 to your computer and use it in GitHub Desktop.
Example of using Channels in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"time" | |
) | |
// Sends messages over the channel | |
func sender(ch chan<- string) { | |
for i := range 5 { | |
if i < 4 { | |
ch <- "Tick!" | |
} else { | |
ch <- "BOOM!" | |
} | |
// Wait a bit until next message is sent | |
time.Sleep(500 * time.Millisecond) | |
} | |
} | |
// Receives messages over the channel | |
func receiver(ch <-chan string) { | |
// Iterate over the channel over time and print the received messages | |
for msg := range ch { | |
log.Println(msg) | |
} | |
} | |
func main() { | |
// Create a channel | |
ch := make(chan string) | |
done := make(chan bool) | |
// Spawn a goroutine for the message receiver | |
go receiver(ch) | |
// Spawn a goroutine for the message sender | |
go func() { | |
// Send messages to the channel | |
sender(ch) | |
// Always close the channel when it's no longer required | |
close(ch) | |
// Send done signal | |
done <- true | |
}() | |
// Wait for the done signal | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment