In this program, we will create a buffered channeland pass the channel into a user-defined function. Here we will receive items from the channel using loop and print them on the console screen.
The source code to receive items from the channel using a loop is given below. The given program is compiled and executed successfully.
// Golang program to receive items
// from a channel using the loop
package main
import "fmt"
func WriteCountryNames(countyNames chan string) {
//Send country names to buffered channel.
countyNames <- "India"
countyNames <- "USA"
countyNames <- "UK"
close(countyNames)
}
func main() {
countyNames := make(chan string, 3)
go WriteCountryNames(countyNames)
//Receive country names from buffered channel.
for val := range countyNames {
fmt.Println(val)
}
}
Output:
India
USA
UK
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.
In the above code, we created a user-defined function WriteCountryNames() that accepts the channel as an argument and here we send country names to the channel.
In the main() function, we created a buffered channel countryNames using the make() function by specifying the type of item and size of the channel. Then we called WriteCountryNames() function to send county names to the channel. After that, we printed the county names using the loop on the console screen.
Program/Source Code:
The source code to receive items from the channel using a loop is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.
In the above code, we created a user-defined function WriteCountryNames() that accepts the channel as an argument and here we send country names to the channel.
In the main() function, we created a buffered channel countryNames using the make() function by specifying the type of item and size of the channel. Then we called WriteCountryNames() function to send county names to the channel. After that, we printed the county names using the loop on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer