#development #golang #pattern

In this blog post, we will explore how to implement an event bus using the Go programming language (Golang) and take advantage of the generics feature introduced in Go 1.18 to make the event bus more flexible and type-safe. Event buses are a fundamental component in event-driven architectures, enabling efficient communication between different parts of your application. By the end of this post, you'll have a solid understanding of how to create a generic event bus in Go.

What is an Event Bus?

An event bus is a publish-subscribe pattern that allows different parts of your application to communicate with each other without needing direct references or dependencies. It consists of three main components: publishers, subscribers, and events.

  • Publishers: These are responsible for generating events and broadcasting them to the event bus.

  • Subscribers: These are entities that listen for specific types of events and perform actions when those events occur.

  • Events: These are data structures that carry information about what has happened. They are sent from publishers to subscribers.

Creating the Event Bus

Let's start by defining the core structure of our event bus. We'll use generics to create a flexible event bus that can handle different types of events.

 1package main
 3import (
 4    "sync"
 7// EventBus represents a generic event bus.
 8type EventBus[T any] struct {
 9    subscribers map[EventType]map[Subscriber]struct{}
10    mutex       sync.Mutex
13// EventType is the type representing different event types.
14type EventType string
16// Subscriber is a function that handles events.
17type Subscriber func(event T)
19// NewEventBus creates a new event bus.
20func NewEventBus[T any]() *EventBus[T] {
21    return &EventBus[T]{
22        subscribers: make(map[EventType]map[Subscriber]struct{}),
23    }
26// Subscribe adds a subscriber for a specific event type.
27func (eb *EventBus[T]) Subscribe(eventType EventType, subscriber Subscriber) {
28    eb.mutex.Lock()
29    defer eb.mutex.Unlock()
31    if eb.subscribers[eventType] == nil {
32        eb.subscribers[eventType] = make(map[Subscriber]struct{})
33    }
35    eb.subscribers[eventType][subscriber] = struct{}{}
38// Unsubscribe removes a subscriber for a specific event type.
39func (eb *EventBus[T]) Unsubscribe(eventType EventType, subscriber Subscriber) {
40    eb.mutex.Lock()
41    defer eb.mutex.Unlock()
43    if subscribers, ok := eb.subscribers[eventType]; ok {
44        delete(subscribers, subscriber)
46        // Cleanup the event type map if there are no subscribers left.
47        if len(subscribers) == 0 {
48            delete(eb.subscribers, eventType)
49        }
50    }
53// Publish sends an event to all subscribers of a specific event type.
54func (eb *EventBus[T]) Publish(eventType EventType, event T) {
55    eb.mutex.Lock()
56    defer eb.mutex.Unlock()
58    if subscribers, ok := eb.subscribers[eventType]; ok {
59        for subscriber := range subscribers {
60            subscriber(event)
61        }
62    }

Using the Event Bus

Now that we have our generic event bus defined, let's see how we can use it in our application.

 1package main
 3import (
 4    "fmt"
 5    "time"
 8func main() {
 9    // Create a new event bus for string events.
10    eventBus := NewEventBus[string]()
12    // Define a subscriber function for string events.
13    stringSubscriber := func(event string) {
14        fmt.Printf("Received string event: %s\n", event)
15    }
17    // Subscribe to a specific event type.
18    eventBus.Subscribe("stringEvent", stringSubscriber)
20    // Publish a string event.
21    eventBus.Publish("stringEvent", "Hello, Event Bus!")
23    // Unsubscribe the subscriber.
24    eventBus.Unsubscribe("stringEvent", stringSubscriber)
26    // The subscriber will not receive events after unsubscribing.
27    eventBus.Publish("stringEvent", "This event won't be received.")
29    // Sleep to allow time for the event bus to finish processing.
30    time.Sleep(time.Second)

In this example, we create an event bus for string events, subscribe to a specific event type ("stringEvent"), publish an event, and then unsubscribe the subscriber. After unsubscribing, the subscriber won't receive any more events of that type.


Implementing an event bus in Go using generics allows you to create a flexible and type-safe communication channel within your application. This can be particularly useful in complex applications where different parts need to communicate without tight coupling. By leveraging the power of generics in Go 1.18, you can create a reusable event bus that works seamlessly with various event types while ensuring type safety.


If you prefer to use a library instead of implementing your own event bus, go-eventbus is a good choice.