We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

State Machine

A state machine is just a fancy word for a system that can be in one of many different states. For example, this function is not a state machine:

func add(a, b int) int {
    return a + b
}

Because it doesn't have any internal state. It just takes two numbers and returns their sum. But this function is a state machine:

type Counter struct {
    count int
}

func (c *Counter) Add(a int) int {
    c.count += a
    return c.count
}

Because it has internal state (the count field), and each time we call Add, it changes the state of the Counter struct. It's not a pure function, it's a stateful function.

We Built a State Machine

The combination of RequestFromReader and Request.parse functions create our state machine. We keep track of several pieces of state:

  • How much data we've read from the io.Reader into the buffer
  • How much data we've parsed from the buffer
  • The current "state" (yeah, yeah, state is a loaded term here) of the parser (initialized, done, etc.)