Read and Write Fibonacci series to Channel in Golang
The main function has two unbuffered channels ch and quit. Inside fibonacci function the select statement blocks until one of its cases is ready.
Example
package main
import (
"fmt"
)
func fibonacci(ch chan int, quit chan bool) {
x, y := 0, 1
for {
select {
case ch <- x: // write to channel ch
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
ch := make(chan int)
quit := make(chan bool)
n := 10
go func(n int) {
for i := 0; i < n; i++ {
fmt.Println(<-ch) // read from channel ch
}
quit <- false
}(n)
fibonacci(ch, quit)
}
0
1
1
2
3
5
8
13
21
34
Most Helpful This Week
Golang Program to Triangle of Alphabets
How to build a map of struct and append values to it?
Golang program for implementation of Levenshtein distance
Go program to find SRV service record of a domain
GO Program to find area and circumference of circle
Golang program for implementation of Linked List
How to remove multiple spaces in a string in GoLang?
Golang program for implementation of ZigZag Matrix
How to Convert Float to String type in Go?
Various examples of printing and formatting in Golang