diff --git a/basics/default-select/main.go b/basics/default-select/main.go new file mode 100644 index 0000000..8508139 --- /dev/null +++ b/basics/default-select/main.go @@ -0,0 +1,25 @@ +package main + +import ( + "log" + "time" +) + +func main() { + tick := time.Tick(100 * time.Millisecond) + + boom := time.After(5000 * time.Millisecond) + + for { + select { + case <-tick: + log.Println("tick.") + case <-boom: + log.Println("boom") + return + default: + log.Println(" .") + time.Sleep(50 * time.Millisecond) + } + } +} diff --git a/basics/main.go b/basics/flow-control/main.go similarity index 100% rename from basics/main.go rename to basics/flow-control/main.go diff --git a/basics/range-close/main.go b/basics/range-close/main.go new file mode 100644 index 0000000..ec1c816 --- /dev/null +++ b/basics/range-close/main.go @@ -0,0 +1,25 @@ +package main + +import ( + "log" +) + +func fibonacci(n int, ch chan int) { + x, y := 0, 1 + for i := 0; i < n; i++ { + ch <- x + x, y = y, x+y + } + close(ch) +} + +func main() { + ch := make(chan int, 10) + + go fibonacci(cap(ch), ch) + for i := range ch { + log.Println(i) + } + + log.Println("Done") +} diff --git a/basics/select/main.go b/basics/select/main.go new file mode 100644 index 0000000..15ee813 --- /dev/null +++ b/basics/select/main.go @@ -0,0 +1,32 @@ +package main + +import "log" + +func fibonacci(ch, quit chan int) { + x, y := 0, 1 + for { + select { + case ch <- x: + x, y = y, x+y + case <-quit: + log.Println("quit") + return + } + } +} + +func main() { + ch := make(chan int, 10) + + quit := make(chan int) + + go func() { + for i := 0; i < cap(ch); i++ { + log.Println(<-ch) + + } + quit <- 0 + }() + + fibonacci(ch, quit) +}