Abstract types
Context-Generic Programming (CGP) extends Rust with pluggable trait implementations, and an abstract type lets the same wiring choose the types those implementations share. Providers can return the same error type without deciding whether it is a string or a domain enum, or carry out calculations using the scalar type their application selects. Rust's associated types express that relationship, and CGP lets each context make the choice through wiring.
This page starts from Rust's associated types, shows how wiring selects one and how providers share it, and ends with what an abstract type does not hide.
Rust already has this
Rust's associated types let a trait name a type that each implementer supplies. For example,
HasScalarType can leave the scalar open while two contexts make different choices:
pub trait HasScalarType {
type Scalar: Copy;
}
impl HasScalarType for HighPrecision {
type Scalar = f64;
}
impl HasScalarType for Embedded {
type Scalar = f32;
}
With a Context: HasScalarType bound, generic code can use Context::Scalar while leaving the
choice between f32 and f64 to the context. Once the context is known, Rust resolves the associated
type. CGP builds on this mechanism, so a direct implementation like either one above is also a valid
way to supply an abstract type in a CGP program.
The important relationship is between the implementing type and its scalar: every use of
HighPrecision::Scalar means f64. A separate generic parameter would leave the scalar open to
callers at each use, whereas an associated type gives all providers working with HighPrecision the
same choice.
Choosing the type by wiring
CGP lets a context select its associated types in the same table as its behavior providers.
#[cgp_type] turns an associated-type trait into a component:
#[cgp_type]
pub trait HasScalarType {
type Scalar: Copy;
}
The generated ScalarTypeProviderComponent is the wiring key, and UseType<T> supplies the concrete
type. These tables make the same choices as the direct implementations above:
delegate_components! {
HighPrecision {
ScalarTypeProviderComponent: UseType<f64>,
}
}
delegate_components! {
Embedded {
ScalarTypeProviderComponent: UseType<f32>,
}
}
Here UseType<f64> supplies f64 as HighPrecision's Scalar, using the provider implementation
generated by #[cgp_type]. The context therefore names only its chosen type in the table. A
provider could also compute the type from further type information, though a fixed choice needs
nothing more than UseType<T>.
That choice still has to meet the trait's bounds. Because Scalar requires Copy, choosing f32
or f64 works, while UseType<String> produces a String: Copy error when checked or used. As with
other wiring, the table alone does not force that check: its requirements are
checked lazily.
One type, agreed on by everything that needs it
Providers that refer to the same context's Scalar share one type choice. An area-calculation
component can use this to return a common scalar for several shape types:
#[cgp_component(ShapeAreaCalculator)]
#[use_type(HasScalarType.Scalar)]
pub trait CanCalculateShapeArea<Shape> {
fn shape_area(&self, shape: &Shape) -> Scalar;
}
In this interface, the context is an application and Shape is the value it measures. The application
chooses the shared result type through HasScalarType, leaving the shape types free of that
requirement. If the providers need only type choices and wiring, even a fieldless struct App; can
serve as the context.
If the application switches from UseType<f32> to UseType<f64>, every shape calculation's
declared result changes with it. For the same implementations to keep working, they must support
the new choice. A provider restricted to Scalar = f64 cannot serve an application choosing f32,
and the abstraction does not supply arithmetic or conversions for either type.
The #[use_type(HasScalarType.Scalar)] attribute makes that relationship visible in the signature.
It imports Scalar as shorthand for <Self as HasScalarType>::Scalar and adds the corresponding
trait bound. Because callers need to name the return type, this bound belongs to the component's
public interface.
Type dependencies without extra parameters
This shared choice can also reduce the parameters a provider needs. Once Context determines
Scalar, code can refer to Context::Scalar without taking a second parameter for it. The same
relationship can hold for an error type or runtime, letting the context collect several choices
that generic code needs to use together.
An implementation can keep a type dependency out of its caller's interface when the type is used
only inside the implementation. If the type appears in a public argument or result, the interface
must expose enough information to name it, as CanCalculateShapeArea does above.
Impl-side dependencies explains that distinction.
A shared error type
HasErrorType gives fallible providers a common error type selected by their context. A provider
can report a concrete source error through CanRaiseError while returning the context's abstract
Error:
#[cgp_component(Loader)]
#[use_type(HasErrorType.Error)]
pub trait CanLoad {
fn load(&self, path: &str) -> Result<String, Error>;
}
#[cgp_impl(new LoadOrFail)]
#[uses(CanRaiseError<String>)]
#[use_type(HasErrorType.Error)]
impl Loader {
fn load(&self, path: &str) -> Result<String, Error> {
if path.is_empty() {
return Err(Self::raise_error("empty path".to_owned()));
}
Ok(format!("contents of {path}"))
}
}
When the path is empty, LoadOrFail reports a String through CanRaiseError. Its context decides
both the error representation and how to turn that source string into it. The same provider can
therefore return anyhow::Error, a domain enum, or String wherever the selected conversion supports
that choice.
Providers that return this context's Error can pass errors between them without converting at
every boundary. Errors from external libraries still need conversion into that common type.
Modular error handling develops this example further.
The provider and the import attribute
The similar names UseType<T> and #[use_type(...)] refer to different parts of this connection.
UseType<T> is the provider in the wiring table that chooses the concrete type. The attribute
imports an associated type and its bound into a definition so the body can use a shorter name.
For example, a context can select UseType<f64> while its providers refer to that choice simply
as Scalar through #[use_type(HasScalarType.Scalar)].
What it costs
Knowing the context can reveal the concrete type again. Code that knows
HighPrecision::Scalar = f64 can use the operations available on f64, so an abstract type does
not by itself conceal a representation from callers. Rust's module privacy is still needed when
access to the representation must be restricted.
Deferring the concrete choice also limits generic code to the bounds it can see. Scalar: Copy
permits copying, but arithmetic and comparison need additional bounds, either on the associated
type or where those operations are used. Putting a bound on the trait makes it available to every
user of the abstract type, while requiring every context's chosen type to satisfy it.
Sharing one choice also means that a non-generic abstract-type trait cannot supply different error types for different purposes within the same context. Those distinctions need their own representation, through separate components, a tagged component, or separate contexts.
An abstract-type component can remain unwired until a use exposes the missing choice. Add
check_components! beside the context's wiring to verify
that the required type is available and satisfies its bounds.
Where to go next
These pages explain related dependencies and the constructs used here:
- Impl-side dependencies: Which requirements can stay inside a provider.
- Implicit arguments: How a provider obtains values from its context.
- Modular error handling: Sharing, constructing, and enriching errors.
#[cgp_type]andUseType: Declaring and selecting an abstract type.#[use_type]: Importing an associated type into a definition.HasType: The built-in component for tagged type choices.- Comparison: ML modules: Abstract-type components beside a signature's abstract
type t, and the sealing CGP does not provide. - Comparison: Implicit parameters: An abstract type as a functional dependency, a type the context determines.
An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.