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:
- Quickstart: install CGP and run a first program in a few minutes.
- Hello World: understand a program like the Quickstart's, then see the same function work on a second context.
- Swap a Storage Backend per Application: build a small application, then give its tests their own storage backend with a component and two providers.
- 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:
- What can CGP do, feature by feature? The Overview.
- Why does CGP work this way? Bypassing coherence and Consumer and provider traits, then the rest of the Concepts.
- Does CGP fit my project? Modularity Hierarchy, and the costs and maturity on the front page.
- How does it compare with what I know? The Comparisons, from dependency injection and type classes to ML modules and dynamic dispatch.
- What does a construct do, or a term mean? The Reference and the Glossary.
- How do I read a CGP compile error? cargo-cgp, CGP's error toolchain.
- What has been built with it? The Projects.
- How do I use CGP with a coding agent? The AI section, with CGP's agent skill.
- Where can I watch a talk about CGP? The Videos page in Resources.
- Where can I ask a question or follow CGP's news? The Community page in Resources.
- How can I help CGP? Contribute.
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.