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.
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.
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.
person
struct with two fields: name
and age
.sync.WaitGroup
to wait for both goroutines to finish and create a channel to communicate person
structs.person
structs.send
function sends a person
struct through the channel and then closes the channel.chan<- person
: Indicates that this channel is only for sending person
structs.close(c)
: Closes the channel after sending the data to signal that no more values will be sent.receive
function receives the person
struct from the channel and prints it.<-chan person
: Indicates that this channel is only for receiving person
structs.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.
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.