How to Implement Pub/Sub with Channels in Go

Implement Go Pub/Sub by creating a channel with make(), sending data via goroutines, and receiving it with the <- operator.

Use make(chan T) to create a channel, then spawn goroutines to send data and a separate goroutine to receive it.

package main

import "fmt"

func main() {
    ch := make(chan string)

    go func() {
        ch <- "Hello from goroutine"
    }()

    msg := <-ch
    fmt.Println(msg)
}
  1. Create an unbuffered channel with ch := make(chan string).
  2. Start a goroutine to send a value using ch <- "value".
  3. Receive the value in the main function using msg := <-ch.
  4. Print the received message to verify the Pub/Sub flow.