# Stepping Through States

Sometimes the states before and after an event are needed, not only the latest one, for example for a history that tells what each event changed. To advance a state by a single stored event, call the `StepStored` function with the state, the state so far, and the event.

It runs the upcasters and the `Evolve` rules exactly as reading from the database does, and returns the next state. A projection that tells what each event changed keeps the state before an event, and steps it. The projection gets the events of every subject, but the state has rules only for the events of its own subjects, and an event of a type without a rule makes `StepStored` fail, and with it the projection. So it steps only the events of the subjects of the state, which a subject scheme tells apart from the others (see **[Composing Subjects](/docs/architecturekit/go/v2.1/composing-subjects)**). Asking `HasRule` instead would skip events of an older type as well, since it knows nothing of upcasters:

```go
books := map[string]Book{}

projection := architecturekit.ProjectionFunc(func(ctx context.Context, event eventsourcingdb.Event) error {
  bookID, ok := bookSubject.Value(event.Subject, "book")
  if !ok {
    // An event of another subject, such as one of a reader.
    return nil
  }

  before := books[bookID]

  after, err := architecturekit.StepStored(bookState, before, event)
  if err != nil {
    return err
  }

  if !before.IsBorrowed && after.IsBorrowed {
    // The book was borrowed by this event.
  }

  books[bookID] = after
  return nil
})
```

For typed events, for example in a test, call the `Step` function instead.

The given state stays unchanged, so both states are at hand afterwards. For a state that holds slices, maps, pointers, channels, functions, or interfaces, such as a field of type `error` or `any`, which can hold any of the others, that takes a `Clone` function (see **[Caching States](/docs/architecturekit/go/v2.1/caching-states)**). Without one, `Step` and `StepStored` return an error of the category `ErrPermanent`, rather than a next state that may share data with the one before. A state that consists of values only needs no `Clone` function.

*Note that a stored event that the upcasters turn into several events is applied in full, and that `FromLatest` has no effect on a single step.*
