ADVERTISEMENT
ADVERTISEMENT

Golang program to pass buffered channel into a user-defined function

Here, we are going to learn how to pass buffered channel into a user-defined function in Golang (Go Language)?
Submitted by Nidhi, on April 03, 2021

Problem Solution:

In this program, we will create a buffered channel and pass the channel into a user-defined function. Here, we will send and receive the item from the channel and print it on the console screen.

Program/Source Code:

The source code to pass the buffered channel into a user-defined function is given below. The given program is compiled and executed successfully.

// Golang program to pass buffered channel
// into a user-defined function

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() {
	//buffered channel
	countyNames := make(chan string, 3)

	go WriteCountryNames(countyNames)

	//Receive country names from buffered channel.
	fmt.Println(<-countyNames)
	fmt.Println(<-countyNames)
	fmt.Println(<-countyNames)
}

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.

func WriteCountryNames(countyNames chan string){
	//Send country names to buffered channel.
	countyNames <- "India"
	countyNames <- "USA"
	countyNames <- "UK"
	
	close(countyNames)
}

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 on the console screen.

Golang Channels Programs »



ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.