Skip to main content

Introduction

Context-Generic Programming (CGP) is a language extension for Rust, with pluggable trait implementations at compile-time. In plain Rust, a type has at most one implementation of each trait. With CGP, you can instead write several implementations of the same trait and decide, for each type that uses it, which one applies.

None of this needs a new language or a new compiler. CGP is a library on stable Rust whose macros expand to ordinary traits and implementations, and the compiler resolves every choice into a direct call. You can bring it into an existing project one trait at a time.

Four terms name the parts of that choice, and the rest of the documentation uses them throughout:

  • Context: a type, such as an application type, that holds the data its implementations need and chooses which implementations it uses.
  • Component: an interface whose implementation a context chooses.
  • Provider: a named implementation of a component.
  • Wiring: the table on a context that selects a provider for each component, resolved at compile time.

Start here​

To start writing code, follow these pages from installation through wiring and checking your own components:

  1. Quickstart: install CGP and run a first program in a few minutes.
  2. Hello World: understand a program like the Quickstart's, then see the same function work on a second context.
  3. Swap a Storage Backend per Application: build a small application, then give its tests their own storage backend with a component and two providers.
  4. Area calculation: turn ordinary Rust functions into components and providers, then learn to check their wiring and understand errors.

Find what you need​

If you came with a particular question, find it below beside the page that answers it:

For releases, design discussions, and talks, visit the blog. Its older posts describe the library as it was when they were published, so for CGP as it is today, rely on the pages above.


An AI agent revised this page using the CGP knowledge base. See How AI is used in this project.