The default case in a select statement executes immediately if no other channel has a value ready. A default case stops the select statement from blocking.
select{casev:=<-ch:// use vdefault:// receiving from ch would block// so do something else}
Ignoring Channels
Sometimes you want to ignore a channel's value. You can do this by not binding it to a variable:
select{case<-ch:// event received; value ignoreddefault:// so do something else}
Alternatively, you can use the blank identifier _ to ignore the value:
select{case_=<-ch:// event received; value ignoreddefault:// so do something else}
Tickers
time.Tick() is a standard library function that returns a channel that sends a value on a given interval.
time.After() sends a value once after the duration has passed.
time.Sleep() blocks the current goroutine for the specified duration of time.
The functions take a time.Duration as an argument. For example:
If you don't add time.Millisecond (or another unit), it will default to nanoseconds. That's β taking a wild guess here β probably faster than you want it to be.
Read-Only Channels
A channel can be marked as read-only by casting it from a chan to a <-chan type. For example:
Write-Only Channels
The same goes for write-only channels, but the arrow's position moves.
Assignment
Like all good back-end engineers, we frequently save backup snapshots of the Textio database.
Complete the saveBackups function.
It should read values from the snapshotTicker and saveAfter channels simultaneously and continuously.
1
If a value is received from snapshotTicker
Call takeSnapshot().
2
If a value is received from saveAfter
Call saveSnapshot() and return from the function.
3
If neither channel has a value ready
Call waitForData() and then time.Sleep() for 500 milliseconds to show in the logs that the snapshot service is running.