How to Implement the Bridge Channel Pattern in Go

Implement the Bridge Channel Pattern in Go by creating a struct with a channel field to decouple data producers from consumers.

The Bridge Channel Pattern is not a built-in Go feature; implement it by creating a struct that holds a channel and methods to send/receive data, effectively decoupling the producer from the consumer logic. Use the import "C" preamble pattern from cgo documentation to define your bridge interface if interacting with C, or standard Go channels for pure Go implementations.

package main

import "fmt"

type Bridge struct {
    data chan string
}

func NewBridge() *Bridge {
    return &Bridge{data: make(chan string)}
}

func (b *Bridge) Send(msg string) {
    b.data <- msg
}

func (b *Bridge) Receive() string {
    return <-b.data
}

func main() {
    bridge := NewBridge()
    go bridge.Send("Hello")
    fmt.Println(bridge.Receive())
}