create a struct channel in go

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.go
type Person struct {
    name string
    age  int
}

func main() {
    people := make(chan Person)

    go func() {
        people <- Person{name: "Alice", age: 30}
        people <- Person{name: "Bob", age: 25}
        close(people)
    }()

    for p := range people {
        fmt.Printf("Name: %s, Age: %d\n", p.name, p.age)
    }
}
336 chars
19 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