To create a channel of struct in Go, we can define a struct type and declare a channel that takes this struct as its element. Here's an example code snippet:
main.go336 chars19 lines
In this example, we define a Person
struct type with two fields: name
and age
. We then declare a channel people
of type chan Person
using the make()
function. Inside a goroutine, we send two Person
structs to the channel and then close the channel.
In the main goroutine, we use a for-range loop to read values from the people
channel until the channel is closed. We print the name and age of each Person
struct using fmt.Printf()
.
This code demonstrates how struct channels can be used to pass data between goroutines in a concurrent Go program.
gistlibby LogSnag