Launches 10 Goroutines and each goroutine adding 10 values to a Channel
The program starts with 10 Goroutines. We created a ch string channel and writing data to that channel by running 10 goroutines concurrently. The direction of the arrow with respect to the channel specifies whether the data is sent or received. The arrow points towards ch specifies we are writing to channel ch. The arrow points outwards from ch specifies we are reading from channel ch.
Example
package main
import (
"fmt"
"strconv"
)
func main() {
ch := make(chan string)
for i := 0; i < 10; i++ {
go func(i int) {
for j := 0; j < 10; j++ {
ch <- "Goroutine : " + strconv.Itoa(i)
}
}(i)
}
for k := 1; k <= 100; k++ {
fmt.Println(k, <-ch)
}
}
1 Goroutine : 9
2 Goroutine : 9
3 Goroutine : 2
4 Goroutine : 0
5 Goroutine : 1
6 Goroutine : 5
7 Goroutine : 3
8 Goroutine : 4
9 Goroutine : 7
10 Goroutine : 6
....................
Most Helpful This Week
Missing return at end of function error in Golang
How to create Slice using Make function in Golang?
Struct Instantiation Using Pointer Address Operator
This sample program demonstrates how to decode a JSON string.
Golang read json file into struct
Example: ReadAll, ReadDir, and ReadFile from IO Package