1. How do you specify the direction of a channel type?
You can specify the direction of a channel using the function signature and the arrow signs:
c chan<- string
means that we can only send to c
c <-chan string
means that we can only receive to c
2. Write your own Sleep
function using time.After
.
package main
import (
"fmt"
"time"
)
func sleep(secs int) {
select {
case <-time.After(time.Duration(secs) * time.Second):
return
}
}
func main() {
fmt.Println(time.Now())
sleep(3)
fmt.Println(time.Now())
}
3. What is a buffered channel? How would you create on with a capacity of 20?
A buffered channel is an asynchronous channel that does not wait unless is at full capacity.
c := make(chan int, 20)