3. Channels Pt.2
v := <-ch<-chfunc downloadData() chan struct{} {
downloadDoneCh := make(chan struct{})
go func() {
fmt.Println("Downloading data file...")
time.Sleep(2 * time.Second) // simulate download time
// after the download is done, send a "signal" to the channel
downloadDoneCh <- struct{}{}
}()
return downloadDoneCh
}
func processData(downloadDoneCh chan struct{}) {
// any code here can run normally
fmt.Println("Preparing to process data...")
// block until `downloadData` sends the signal that it's done
<-downloadDoneCh
// any code here can assume that data download is complete
fmt.Println("Data download complete, starting data processing...")
}
processData(downloadData())
// Preparing to process data...
// Downloading data file...
// Data download complete, starting data processing...Channels - Signaling Without Data
Receiving Without Storing
Normal Receive (Store the Value)
Signal Receive (Discard the Value)
Why Use This?
Empty Struct: struct{}
struct{}Creating and Sending Empty Struct
Complete Example Breakdown
Flow Diagram
Real-World Example: Multiple Workers
Comparison: With vs Without Data
With Data (Need the Result)
Without Data (Just Need to Know It's Done)
Understanding struct{}{}
struct{}{}Common Patterns
Pattern 1: Wait for Single Task
Pattern 2: Wait for Multiple Tasks
Pattern 3: Notify When Ready
Why Not Just Use bool?
bool?Key Takeaways
Quick Reference
Operation
Syntax
Purpose