Advertisement

In the previous blog, we learned about channels in Golang, Deadlock, Types of channels. This time we will take a look at Golang Empty Struct Channel also known as Signal Only Channel.

Learn about Golang Channel and Deadlock, Types of Channels, Buffered Channels.

Golang Struct Channel

Channels in Golang can also send and receive Structs.

type data struct {
	audio string
	video string
}

var d = make(chan data, 50)

func display() {
	for data := range d {
		fmt.Println(data)
	}
}

func main() {

	go display()

	d <- data{"Audio Data 1", "Video Data 1"}
	d <- data{"Audio Data 2", "Video Data 2"}
	d <- data{"Audio Data 3", "Video Data 3"}

	time.Sleep(100 * time.Millisecond)

}

{Audio Data 1 Video Data 1}
{Audio Data 2 Video Data 2}
{Audio Data 3 Video Data 3}

Golang Empty Struct Channel

Whenever a channel is declared, whatever may be its type memory is allocated. But When Empty Struct is Used as Type, no memory is allocated and is used as only Signal only Channel.

Declaration Syntax:

var soc = make( chan struct{}, 50)

Example:

var d = make(chan struct{}, 50)

func display() {
	for data := range d {
		fmt.Println(data)
	}
}
func main() {

	go display()
	d <- struct{}{}
	time.Sleep(100 * time.Millisecond)

}

Output:

{}

This is used as a signal only channel. we pass signals from the Empty Struct Channel.

Signal-only channels are useful when you are monitoring channels using a select statement and you need a way to exit monitoring. Check if a signal-only channel is received and then exit out of the loop.

Learn more about Channels in Golang from the official Documentation.

About Author
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top