×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to demonstrate the channel with switch block

Here, we are going to demonstrate the channel with switch block in Golang (Go Language).
Submitted by Nidhi, on April 04, 2021 [Last updated : March 04, 2023]

How to implement the channel with switch block in Golang?

Problem Solution:

In this program, we will create two channels to store Boolean value. Here, we will send Boolean values to channels in user-defined function and then received values and print appropriate message using switch() block on the console screen.

Program/Source Code:

The source code to demonstrate the channel with the switch block is given below. The given program is compiled and executed successfully.

Golang code to implement the channel with switch block

// Golang program to demonstrate the channel
// with switch block

package main

import "fmt"

func SetChannels(chnl1 chan bool, chnl2 chan bool) {
	chnl1 <- true
	chnl1 <- false
}

func main() {
	channel1 := make(chan bool)
	channel2 := make(chan bool)

	go SetChannels(channel1, channel2)

	switch <-channel1 {
	case true:
		fmt.Println("Hello")
	case false:
		fmt.Println("Hiiii")
	}
}

Output:

Hello

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 main() function, we created two channels. Then we send values to channels in SetChannels() function. After that, we received using switch() block and printed the appropriate message on the console screen.

Golang Channels Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.