Notifications 0
Sending Structs Between Goroutines in Go
Sultan Khan - March 29, 2025
Golang's concurrency model is one of its standout features, enabling developers to build highly concurrent and efficient programs. One common requirement is to send data between goroutines. This blog post will demonstrate how to send a struct from one goroutine to another using channels. We'll use a simple example with a person struct to illustrate the concept.
Introduction
In Go, goroutines are lightweight threads managed by the Go runtime. Channels are the conduits through which goroutines communicate. They provide a way to send and receive values of a specific type between concurrent goroutines. Let's explore how to send a struct via a channel between two goroutines.
Example: Sending a Struct
Here's a complete example in Go where we define a person struct, create two goroutines, and send an instance of the person struct from one goroutine to another via a channel.
The Code
Explanation
- Struct Definition: We define a simple
personstruct with two fields:nameandage.
- Main Function: We initialize a
sync.WaitGroupto wait for both goroutines to finish and create a channel to communicatepersonstructs.
- WaitGroup: Ensures that the main function waits for both goroutines to complete before exiting.
- Channel: A typed channel for sending
personstructs. - Sending Goroutine: The
sendfunction sends apersonstruct through the channel and then closes the channel.
chan<- person: Indicates that this channel is only for sendingpersonstructs.close(c): Closes the channel after sending the data to signal that no more values will be sent.- Receiving Goroutine: The
receivefunction receives thepersonstruct from the channel and prints it.
<-chan person: Indicates that this channel is only for receivingpersonstructs.
Running the Code
When you run the above code, you should see the following output:
This output demonstrates that the person struct was successfully sent from one goroutine to another via the channel.
Conclusion
Sending structs between goroutines in Go is straightforward with the use of channels. Channels provide a powerful mechanism for communication between goroutines, ensuring that data is safely passed around without the need for explicit locking. This simple example demonstrates the basics, and you can extend this pattern to more complex scenarios in your concurrent Go programs.