Skip to content
Go

Building a Small ECS in Go

A simple, practical introduction to entity-component systems in Go, with a complete implementation you can understand and extend.

Disclaimer: I am not an expert in ECS or Go. This is a simple, educational implementation intended to explain the basic ideas behind an entity-component system. I am writing this article to learn, experiment, and enjoy the process of sharing what I discover.

An entity-component system (ECS) is one way to organise data and the code that works on it. You will often see ECS in games and simulations, where the program has to update a lot of objects every frame.

The idea sounded more complicated to me at first, so I wanted to start with the smallest version I could make. We will build a small ECS in Go from scratch. By the end, we will have entities with position and velocity components, plus a system that moves them.

This is not intended to be a production-ready ECS library. The goal is to make the basic relationships visible and leave the more advanced parts for later.

Why am I starting with such a small version?

It is tempting to begin with generics, archetypes, event queues, and a high-performance query API. Those features are useful in the right project, but adding all of them now would hide the basic idea behind a lot of code.

For this first version, I am making a few deliberate trade-offs:

  • Entities start at 1, so the zero value can remain an obvious “no entity” value.
  • Component data is stored in ordinary Go maps, not an optimised storage layout.
  • Systems are plain functions instead of types that implement an interface.

These choices are not meant to be rules for every ECS. They just keep this example small enough to read in one sitting and change without being afraid of breaking something.

ECS compared with an OOP design

In an object-oriented design, we might put the player’s data and behaviour in one type:

go
type Player struct {
	Position Position
	Velocity Velocity
	Health   int
}

func (p *Player) Move(deltaTime float64) {
	p.Position.X += p.Velocity.X * deltaTime
	p.Position.Y += p.Velocity.Y * deltaTime
}

This approach is perfectly reasonable for many programs. A Player owns its state, and calling player.Move() is easy to understand. At this point, we could add separate Enemy, Bullet, and NPC types as the project grows.

The awkward part appears when several different types need the same behaviour. Should an enemy and a bullet both inherit from a Movable type? What happens when an object can move and take damage, but does not fit neatly into one class? These questions do not make OOP wrong, but they can make the class hierarchy harder to change as features accumulate.

ECS takes a different approach:

text
Entity 7 -> Position, Velocity, Health
Entity 8 -> Position, Velocity
Entity 9 -> Position, Damage

There is no Player object in this model. Entity 7 is just an ID, and the components describe what it can do. A movement system processes entities with Position and Velocity, whether they represent players, enemies, or bullets.

There can also be a performance benefit when component storage is designed around packed arrays. A movement system can walk through positions and velocities that are next to one another in memory. CPUs tend to handle this well because of cache locality, and the system does not have to load unrelated fields from a large object. This is one part of what people mean by data-oriented design.

That benefit is not automatic, though. The small ECS in this article uses Go maps because they are easier to understand, so it does not have the same memory layout as a high-performance ECS. Packed arrays or archetype storage are things to consider after profiling, not something we need to add before the example works.

Neither approach is automatically better. OOP can be a clear choice when objects have distinct behaviour and the number of types is small. ECS becomes interesting when many objects share different combinations of data and need to be processed in groups. That is the approach I want to explore in the rest of this article.

What is an ECS?

An ECS separates three things:

  • Entities are identifiers. An entity might represent a player, an enemy, or a bullet.
  • Components are data. A position, velocity, or health value is a component.
  • Systems are functions that operate on entities with specific components.

For example, a moving player could look like this:

text
Entity 7
  Position: (10, 20)
  Velocity: (2, 0)
  Health: 100

The movement system does not need to know that entity 7 is a player. It only cares that the entity has both Position and Velocity. That small distinction is the part of ECS I find most useful.

This is different from a traditional object-oriented design where a Player object might contain its data and movement method. ECS keeps data and behaviour separate, which makes it easy to add the same behaviour to many different kinds of entities.

The design for our example

Our small ECS will use:

  1. An integer as the entity identifier.
  2. One Go map for each component type.
  3. A World that owns entities and components.
  4. A movement system that reads velocity and changes position.

This map-based design is easy to read. High-performance ECS libraries usually store components in denser arrays or use specialised queries, but the fundamental idea is the same.

Creating the world

Let us start with an entity type and a world:

go
package main

import "fmt"

type Entity uint32

type World struct {
	nextEntity Entity
	positions   map[Entity]Position
	velocities  map[Entity]Velocity
}

type Position struct {
	X float64
	Y float64
}

type Velocity struct {
	X float64
	Y float64
}

func NewWorld() *World {
	return &World{
		positions:  make(map[Entity]Position),
		velocities: make(map[Entity]Velocity),
	}
}

func (w *World) CreateEntity() Entity {
	w.nextEntity++
	return w.nextEntity
}

Entity is only an ID. It does not contain position, velocity, or any other data.

The world owns a separate map for each component type. If an entity is not in the positions map, it does not have a position component. This gives us a simple way to represent component composition without creating a large inheritance tree.

Adding and reading components

The world needs a few methods for attaching and retrieving components:

go
func (w *World) AddPosition(entity Entity, position Position) {
	w.positions[entity] = position
}

func (w *World) AddVelocity(entity Entity, velocity Velocity) {
	w.velocities[entity] = velocity
}

func (w *World) Position(entity Entity) (Position, bool) {
	position, ok := w.positions[entity]
	return position, ok
}

The bool return value is important. A caller can distinguish between a position containing zeroes and an entity that does not have a position at all.

Go maps return a copy of a struct. Therefore, this code does not update the position in the world:

go
position, ok := world.Position(entity)
if ok {
	position.X += 1 // Changes only the local copy.
}

For systems that need to update data, the world should provide a setter:

go
func (w *World) SetPosition(entity Entity, position Position) {
	w.positions[entity] = position
}

Using a setter is a little more explicit, and it keeps the map implementation private.

Writing a system

A system is just ordinary Go code. It looks at the component maps it needs and updates the entities that match:

go
func MoveSystem(world *World, deltaTime float64) {
	for entity, velocity := range world.velocities {
		position, ok := world.positions[entity]
		if !ok {
			continue
		}

		position.X += velocity.X * deltaTime
		position.Y += velocity.Y * deltaTime
		world.positions[entity] = position
	}
}

This system naturally selects entities with both components:

  • An entity with only Velocity is ignored.
  • An entity with only Position is ignored.
  • An entity with both is moved.

There is no special Movable type and no registration step. The component data itself determines which entities the system can process.

deltaTime is the elapsed time since the previous update, in seconds. If an entity moves at 2 units per second and deltaTime is 0.5, it moves 1 unit in that update.

Putting it together

Here is a complete program using the world and movement system:

go
package main

import "fmt"

type Entity uint32

type Position struct {
	X float64
	Y float64
}

type Velocity struct {
	X float64
	Y float64
}

type World struct {
	nextEntity Entity
	positions   map[Entity]Position
	velocities  map[Entity]Velocity
}

func NewWorld() *World {
	return &World{
		positions:  make(map[Entity]Position),
		velocities: make(map[Entity]Velocity),
	}
}

func (w *World) CreateEntity() Entity {
	w.nextEntity++
	return w.nextEntity
}

func (w *World) AddPosition(entity Entity, position Position) {
	w.positions[entity] = position
}

func (w *World) AddVelocity(entity Entity, velocity Velocity) {
	w.velocities[entity] = velocity
}

func MoveSystem(world *World, deltaTime float64) {
	for entity, velocity := range world.velocities {
		position, ok := world.positions[entity]
		if !ok {
			continue
		}

		position.X += velocity.X * deltaTime
		position.Y += velocity.Y * deltaTime
		world.positions[entity] = position
	}
}

func main() {
	world := NewWorld()

	player := world.CreateEntity()
	world.AddPosition(player, Position{X: 10, Y: 20})
	world.AddVelocity(player, Velocity{X: 4, Y: 0})

	stationary := world.CreateEntity()
	world.AddPosition(stationary, Position{X: 5, Y: 5})

	MoveSystem(world, 0.5)

	fmt.Printf("player:    %+v\n", world.positions[player])
	fmt.Printf("stationary: %+v\n", world.positions[stationary])
}

The output is:

text
player:    {X:12 Y:20}
stationary: {X:5 Y:5}

The player moved because it has both Position and Velocity. The stationary entity stayed where it was because it has no velocity component.

There is one small detail hidden in this example: Go deliberately does not guarantee map iteration order. That does not matter for MoveSystem, because each entity is updated independently. It would matter for a system where one entity affects another, so those systems would need an explicit ordering strategy.

Adding another system

Once the world exists, we can add behaviour without changing the entity type. For example, a gravity system can update every velocity:

go
func GravitySystem(world *World, deltaTime float64) {
	for entity, velocity := range world.velocities {
		velocity.Y -= 9.8 * deltaTime
		world.velocities[entity] = velocity
	}
}

The order of systems matters. For this example, a simple update loop might be:

go
for frame := 0; frame < 60; frame++ {
	GravitySystem(world, 1.0/60.0)
	MoveSystem(world, 1.0/60.0)
}

Gravity changes the velocity first, and movement then uses the new velocity. Other games might move first and apply gravity afterward. The important part is to choose an order deliberately.

Deleting entities

The example can create entities, but a real program also needs to remove them. Deletion means removing the entity’s components:

go
func (w *World) DestroyEntity(entity Entity) {
	delete(w.positions, entity)
	delete(w.velocities, entity)
}

This is enough for the example. Larger ECS implementations usually also track which entities are alive, recycle IDs safely, and remove every component type when an entity is destroyed.

If this were becoming a real package, I would also add tests around entity creation, component lookup, movement, and destruction before adding more features. Small tests are especially helpful here because ECS bugs often come from an entity accidentally having one component but not another.

What this simple design does well

This implementation is a good starting point because it is:

  • Easy to understand: entities are IDs, components are maps, and systems are functions.
  • Flexible: adding a Health component does not require changing Entity.
  • Testable: systems can be tested with a small world and a few entities.
  • Explicit: the required components are visible in each system.

It is also a useful design for tools, prototypes, simulations, and small games where simplicity matters more than maximum throughput.

Where it will need to grow

Maps are not always the fastest way to process thousands of entities. A map lookup can be less cache-friendly than iterating over a packed slice. If profiling shows that component processing is a bottleneck, possible next steps include:

  • Store components in slices indexed by entity ID.
  • Keep a list of entities that have each component.
  • Add a query API such as Query(Position, Velocity).
  • Group entities with the same component combination into archetypes.
  • Add a generic component store if the project benefits from generics.

These features add complexity. It is usually better to start with a design that is easy to verify, then optimise the parts that profiling identifies.

Conclusion

After writing this small example, my main takeaway is that an ECS does not need a complicated framework. A world, entity IDs, component stores, and a few systems are enough to show the core idea.

The map-based implementation here is a reasonable place to start. It is not the fastest design, but it is easy to inspect while learning. I would keep the systems focused and introduce queries or more efficient storage only when the project actually needs them.

In the next part, we will build a more practical ECS and use Raylib to create something interactive. That will give us a chance to move beyond small console examples and see how entities, components, and systems work together inside a real-time program.