Functions and Getters
Use implicit arguments and function macros for routine CGP field access and operations. Getter
traits expose named accessors when other code needs them. This reference explains those choices and
the HasField operations they generate.
How field access works underneath: HasField
HasField<Tag> lets a provider read a field without naming the concrete context type. For example,
Context: HasField<Symbol!("name"), Value = String> requires access to a String field tagged
name. The provider can use that field through the trait while remaining generic over its context.
This is an impl-side dependency: the implementation requires it, but the consumer
interface does not expose it.
The examples use CGP v0.8.0 and assume use cgp::prelude::*;, with HasField from
cgp::core::field::traits and UseField from cgp::core::field::impls.
HasField declares the field’s type as Value and returns a reference to it. The
PhantomData<Tag> argument identifies which field to read when several impls are available:
pub trait HasField<Tag> {
type Value;
fn get_field(&self, _tag: PhantomData<Tag>) -> &Self::Value;
}
Tags identify named fields with Symbol!("field_name") and tuple fields with Index<N>. These
type-level primitives encode the field name or position, and
PhantomData<Tag> supplies the tag at the call site. For mutable access,
HasFieldMut<Tag>: HasField<Tag> adds get_field_mut, returning &mut Self::Value.
Let Rust infer the tag with self.get_field(PhantomData) when the bounds identify a single field.
Use self.get_field(PhantomData::<Symbol!("name")>) when several fields could match. Here, the
bound identifies the name field:
#[cgp_impl(new GreetHello)]
impl Greeter
where
Self: HasField<Symbol!("name"), Value = String>,
{
fn greet(&self) {
println!("Hello, {}!", self.get_field(PhantomData));
}
}
Use the HasField derive to generate field-access impls for ordinary structs.
Generating field access: #[derive(HasField)]
#[derive(HasField)] generates a HasField and HasFieldMut impl for each field while preserving
the struct definition. This exposes ordinary struct fields to generic code through trait bounds:
#[derive(HasField)]
pub struct Person {
pub name: String,
pub age: u8,
}
The derive keys each named field by its Symbol! tag. For name, it generates
impl HasField<Symbol!("name")> for Person { type Value = String; … } with a method returning
&self.name, plus the mutable impl. It does the same for age, so Person satisfies the earlier
GreetHello bound. Tuple fields use positional tags instead:
#[derive(HasField)]
pub struct Rectangle(pub f64, pub f64);
// → impl HasField<Index<0>> for Rectangle { type Value = f64; … &self.0 }
// → impl HasField<Index<1>> for Rectangle { type Value = f64; … &self.1 }
The generated impls preserve the struct’s generic parameters. Field access also follows smart
pointers through a blanket HasField impl for Deref targets, so Box<Person> can expose the
inner fields. The field access generated by #[cgp_fn], #[implicit], and getter macros depends on
these HasField bounds.
Single-implementation traits: #[cgp_fn]
Use #[cgp_fn] for an operation with one implementation. It generates a trait and a blanket impl
for every context satisfying the function’s dependencies, without a provider struct or wiring table.
Use a full component when contexts need to select among providers.
The function name becomes the method name, and its PascalCase form becomes the default trait name.
For example, rectangle_area defines the RectangleArea trait:
#[cgp_fn]
pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 {
width * height
}
The generated RectangleArea method takes only &self. Each implicit argument becomes a HasField
bound and a binding at the start of the blanket impl’s body:
/// The trait for the `rectangle_area` operation.
pub trait RectangleArea {
/// The `rectangle_area` operation.
fn rectangle_area(&self) -> f64;
}
impl<__Context__> RectangleArea for __Context__
where
Self: HasField<Symbol!("width"), Value = f64>
+ HasField<Symbol!("height"), Value = f64>,
{
fn rectangle_area(&self) -> f64 {
let width: f64 = self.get_field(PhantomData::<Symbol!("width")>).clone();
let height: f64 = self.get_field(PhantomData::<Symbol!("height")>).clone();
width * height
}
}
The blanket impl uses the reserved context parameter __Context__, referenced as Self inside the
impl. Override the default trait name with an attribute argument:
#[cgp_fn(CanCalculateRectangleArea)] names the trait CanCalculateRectangleArea.
Function generics appear on both the generated trait and its impl. The function’s where bounds
appear only on the impl as impl-side dependencies. This generic area function illustrates the
distinction:
#[cgp_fn]
pub fn rectangle_area<Scalar>(
&self,
#[implicit] width: Scalar,
#[implicit] height: Scalar,
) -> Scalar
where
Scalar: Mul<Output = Scalar> + Copy,
{
width * height
}
Scalar becomes a parameter of RectangleArea<Scalar> and its impl. The Mul and Copy bounds
remain on the impl, before the implicit HasField bounds. Only the bounds #[use_type] and
#[use_provider] add come after those.
#[cgp_fn] does not generate method-level generic parameters. If a method needs its own generics,
write an explicit blanket impl or a full component.
Field access dressed as a function argument: #[implicit]
Prefer #[implicit] arguments for reading fields from a provider’s context. They make field
dependencies look like function parameters, so basic code can use them without directly handling
HasField, Symbol!, or PhantomData.
An implicit argument’s name selects the field, and its type determines the access operation. The
macro removes the argument from the public signature, adds the corresponding HasField bound, and
binds the field value at the start of the body. For example, #[implicit] width: f64 requires a
field named width of type f64.
Owned implicit arguments clone the field value, leaving the context unchanged. An argument such as
f64 or String reads the field by reference and calls .clone(). The &str shorthand instead
borrows any AsRef<str> field through .as_ref(), so a String, a Cow<str>, or a Box<str> field
all work and none of them needs an allocator:
#[cgp_fn]
pub fn greet(&self, #[implicit] name: &str) {
println!("Hello, {}!", name);
}
// bound: HasField<Symbol!("name"), Value: AsRef<str> + 'static>
// binding: let name: &str = self.get_field(PhantomData::<Symbol!("name")>).as_ref();
Option<&str> works the same way through the OptionAsRef helper trait: the bound is
Value: OptionAsRef<str> + 'static and the binding appends .option_as_ref(), so an
Option<String>, an Option<Cow<str>>, or an Option<Box<str>> field all work.
An implicit argument requires self as the function’s first argument and a bare identifier as its
pattern. Destructuring and mut patterns are rejected; create a mutable local inside the body when
needed. Multiple immutable implicit arguments can share the context borrow.
A mutable implicit argument must be the only implicit argument and requires a &mut self receiver.
It reads through get_field_mut, which borrows the entire context exclusively. The argument’s type
determines whether access is mutable; a mutable receiver alone does not.
Mutable forms mirror the shared access rules. &mut T borrows a field directly, &mut [T] uses
AsMut<[T]>, Option<&mut T> uses .as_mut(), and Option<&mut str> borrows an Option<String>
through .as_deref_mut().
MRef<'_, T> always performs a shared read. It borrows a T field and
wraps it as MRef::Ref(..), even with a &mut self receiver. It does not have a mutable
counterpart and lets the body accept an owned-or-borrowed value.
Use #[implicit] in #[cgp_fn] or methods of a #[cgp_impl] provider. Both generate the same
access operations; in a provider, the field bounds join the impl’s where clause.
Importing trait dependencies: #[uses]
Use #[uses(...)] to declare the traits a function or provider implementation requires of its
context. It
adds a Self bound for each listed trait, allowing the body to call its methods. For example,
#[uses(RectangleArea)] generates Self: RectangleArea.
The imported trait can be an ordinary Rust trait. #[uses(Display)] and #[uses(AsRef<[u8]>)] are
accepted and preferred over equivalent handwritten bounds. The following function imports
RectangleArea and combines it with an implicit scale factor:
#[cgp_fn]
#[uses(RectangleArea)]
pub fn scaled_rectangle_area(&self, #[implicit] scale_factor: f64) -> f64 {
self.rectangle_area() * scale_factor * scale_factor
}
The generated impl requires both RectangleArea and the scale_factor field. The imported
trait remains an impl-side dependency and is not added to the generated trait.
Prefer the simple TraitIdent<Params> form for trait imports. Associated-type bindings such as
HasErrorType<Error = AppError> are also accepted, but use the #[use_type] equality
form for abstract types. #[use_type(HasErrorType.{Error = AppError})] adds the
bound and rewrites references to the type.
Combine trait imports in one comma-separated attribute, such as
#[uses(CanQueryUserBalance, CanRaiseHttpError<ErrNotFound, String>)]. #[uses] works on both
#[cgp_fn] and #[cgp_impl], and the imported trait can be defined through either form.
Adding supertraits and trait bounds: #[extend] and #[extend_where]
Use #[extend(...)] for a public supertrait requirement. #[uses] adds a hidden implementation
dependency, while #[extend] adds a bound that every implementor must satisfy and callers can rely
on. In #[cgp_fn], it adds both the supertrait and an impl bound; ordinary function where clauses
affect only the impl.
The example uses HasScalarType to show the supertrait’s effect on the method signature. In
application code, prefer #[use_type] for abstract-type supertraits and reserve #[extend] for
supertraits that contribute methods:
pub trait HasScalarType {
type Scalar: Clone + Mul<Output = Self::Scalar>;
}
#[cgp_fn]
#[extend(HasScalarType)]
pub fn rectangle_area(
&self,
#[implicit] width: Self::Scalar,
#[implicit] height: Self::Scalar,
) -> Self::Scalar {
width * height
}
// → pub trait RectangleArea: HasScalarType { fn rectangle_area(&self) -> Self::Scalar; }
#[extend] accepts the simplified TraitIdent<Params> form used by #[uses]. It also works on
#[cgp_component], where it is the preferred syntax for non-type supertraits. Use
#[use_type] when signatures name an imported associated type, because it adds the supertrait and
rewrites the type references.
A component's supertrait binds its callers, not its providers. The provider trait carries it as a
where bound on the context, which an impl must prove rather than inherit, so every #[cgp_impl]
provider of a #[extend(HasName)] component also writes #[uses(HasName)], even when its body does
not call name(). Without it the provider fails with E0277 (__Context__: HasName is not
satisfied), which cargo cgp check reports as [CGP-E036].
#[extend_where(...)] adds where predicates to the trait generated by #[cgp_fn]. It accepts
arbitrary predicates, including associated-type equality, so it can place a public requirement on a
generic parameter:
#[cgp_fn]
#[extend_where(Scalar: Clone)]
pub fn rectangle_area<Scalar>(/* … */) -> Scalar
where
Scalar: Mul<Output = Scalar>,
{ /* … */ }
// → pub trait RectangleArea<Scalar> where Scalar: Clone { fn rectangle_area(&self) -> Scalar; }
#[extend_where] makes a bound a precondition for using the trait; it does not make callers inherit
that bound. In the example, Scalar: Mul remains an impl-side dependency, while Scalar: Clone
appears on the trait. Generic callers must still state Scalar: Clone themselves. Supertraits added
by #[extend] are available to callers through their trait bound.
Moving a bound onto the trait makes invalid uses fail earlier. Ctx: RectangleArea<NoClone>
produces E0277 with a required by a bound in RectangleArea note. If Clone remained only on the
impl, the generic bound would be accepted until a concrete context required that impl.
Getter traits: #[cgp_auto_getter]
Prefer implicit arguments for fields on the
provider’s own context. They borrow plain &T arguments without cloning and cover fields used by
several providers. A getter trait adds a named accessor such as self.name(), with
#[cgp_auto_getter] generating access to the field of the same name. Use a getter when an implicit
argument cannot express the required access:
- Access on another type: Require a getter bound such as
Request: HasBasicAuthHeader<Self>when the field belongs to a value other than the provider's context. - Named accessor: Expose an accessor that other code requires through
#[uses(HasName)]or a supertrait. - Abstract field type: Infer an associated type from the field while keeping it abstract for callers.
The macro does not accept arguments and preserves the trait definition. It adds a blanket impl over
__Context__ that selects the field using the method name as a Symbol! tag:
#[cgp_auto_getter]
pub trait HasName {
fn name(&self) -> &str;
}
// generated:
impl<__Context__> HasName for __Context__
where
__Context__: HasField<Symbol!("name"), Value = String>,
{
fn name(&self) -> &str {
self.get_field(PhantomData::<Symbol!("name")>).as_ref()
}
}
Auto-getters use the same access rules as implicit arguments, except that a &str getter keeps the
String field, because its HasField bound is also used by the WithProvider adapter. Shared
getters borrow or clone according to the return type, while mutable getters require a &mut self
receiver and use get_field_mut.
The return type determines the field type and read operation:
| Return type | Field type or bound | Operation |
|---|---|---|
&T | T | Borrow directly |
&str | String | .as_ref() |
Option<&T> | Option<T> | .as_ref() |
Option<&str> | Option<String> | .option_as_ref() |
&[T] | AsRef<[T]> | .as_ref() |
MRef<'_, T> | T | Wrap the borrow as MRef::Ref(..) |
| Owned path, tuple, or array | Matching field type | .clone() |
&mut T | T | Borrow mutably |
&mut str | String | .as_mut() |
&mut [T] | AsMut<[T]> | .as_mut() |
Option<&mut T> | Option<T> | .as_mut() |
Option<&mut str> | Option<String> | .as_deref_mut() |
MRef lets an accessor return an owned or borrowed value; the generated
getter supplies the borrowed form.
A getter takes its access mode from the receiver, not the return type, which differs from an
implicit argument. So a &mut self getter returning a shared Option<&T> or Option<&str> fails
with E0308, because the body converts with .as_mut(); return Option<&mut T> or take &self.
The Option<&T> form needs a sized T, in a getter and an implicit argument alike. The macro
rejects Option<&[T]> and Option<&dyn Trait> with a message naming the sized container to read,
such as Option<&Vec from an Option<Vec<T>> field. An unsized type named by a path, such as
Option<&Path>, reaches the compiler as an E0277 on the attribute; return Option<&PathBuf>
instead.
A trait can declare several getter methods. Each method selects its own field and generates a
corresponding bound and body. For example, fn width(&self) -> &f64; fn height(&self) -> &f64;
generates access to both fields.
A single-method getter can infer a local associated type from its field. Declare exactly one method
returning &Self::AssocType. The macro adds an impl parameter for the associated type and binds it
through the field’s Value:
#[cgp_auto_getter]
pub trait HasName {
type Name: Display;
fn name(&self) -> &Self::Name;
}
// → impl<__Context__, Name> HasName for __Context__
// where Name: Display, __Context__: HasField<Symbol!("name"), Value = Name>
// { type Name = Name; … }
A getter can read from another type by accepting a typed reference as its first argument. The first
argument need not be self, so the context can name a type whose field the getter reads:
#[cgp_auto_getter]
pub trait HasFooBar: HasFooType + HasBarType {
fn foo_bar(foo: &Self::Foo) -> &Self::Bar;
}
// → bound falls on __Context__::Foo, not on the context:
// __Context__::Foo: HasField<Symbol!("foo_bar"), Value = __Context__::Bar>
// and the method is called as an associated function: App::foo_bar(&foo)
The macro rewrites Self in argument and return types to the context type. A shared or mutable
first reference determines the access mode. This supports field access on another type, which
implicit arguments cannot perform.
A getter may accept one additional PhantomData argument, as in
fn foo(&self, _tag: PhantomData<Foo>) -> &Foo;. The generated method preserves that argument but
does not use it for field lookup. Other additional argument types are rejected. #[cgp_getter] uses
the same parser and accepts both method forms.
A context with a matching HasField impl gains the auto-getter without wiring. The field name must
match the method name, and the generated implementation cannot be replaced. Use #[cgp_getter] only
when the context needs to choose a different source field or provider.
Use #[use_type] with in Context when a getter’s return type belongs to a
generic parameter rather than Self. This supplies the required bound and avoids handwritten
projections:
#[cgp_auto_getter]
#[use_type(HasUserIdType.UserId in App)]
pub trait HasLoggedInUser<App> {
fn logged_in_user(&self) -> &Option<UserId>;
}
The in App clause adds App: HasUserIdType to the generated trait and rewrites UserId to
<App as HasUserIdType>::UserId. The plain <App> parameter is sufficient; neither the bound nor
the qualified path needs to be repeated.
Wireable getters: #[cgp_getter] and UseField
Reserve #[cgp_getter] for contexts that must select a getter’s source field or provider through
wiring. It defines a full component and accepts the same method forms
as #[cgp_auto_getter]. Prefer implicit arguments or auto-getters for routine access.
The provider name defaults to the trait name with a leading Has removed and Getter appended.
HasName therefore produces NameGetter and NameGetterComponent. Override the provider name with
an argument such as #[cgp_getter(GetName)]. A trait whose name does not start with Has has no
default and must pass one, or it fails with the `provider` key must be given.
The generated UseField<Tag> impl lets wiring select a field independently of the method name.
UseField is a zero-sized provider containing only PhantomData; it is named in wiring and never
instantiated. Here, the name method reads first_name:
#[cgp_getter]
pub trait HasName {
fn name(&self) -> &str;
}
#[derive(HasField)]
pub struct Person {
pub first_name: String,
}
delegate_components! {
Person {
NameGetterComponent: UseField<Symbol!("first_name")>,
}
}
// person.name() now reads the first_name field
The entry NameGetterComponent: UseField<Symbol!("first_name")> selects the field for name. The
generated provider impl leaves the field tag generic, while an auto-getter fixes it to the method
name.
#[cgp_getter] also generates a UseFields provider that reads fields by method name. Only a
single-method getter receives the UseField<Tag> impl and the WithProvider adapter, since both
presuppose one field; a multi-method getter wired to UseField fails with an unmet IsProviderFor
bound that never mentions the method count, so wire UseFields or split the trait.
Use UseFieldRef<Tag, Value> when AsRef or AsMut converts the stored field to the exposed type,
for a getter returning &Value with Value sized. For example, a fn config(&self) -> &Config
getter wired to WithFieldRef<Symbol!("config"), Config> reads a field holding a wrapper that
implements AsRef<Config>. It cannot serve a -> &str getter, since str is unsized and the getter
macros already read a String field for that return type; plain UseField covers &str, &[T],
and Option<&T> returns. Import this provider from cgp::core::field::impls; it is not in the
prelude, and it is wired only through its WithFieldRef alias.
WithField and WithFieldRef are the WithProvider aliases for UseField and UseFieldRef; see
wiring. An entry such as NameGetterComponent: WithField<Symbol!("first_name")>
supplies the getter from that named field.
Reaching a nested field with ChainGetters
Use ChainGetters<Getters> to reach a field through nested values. It applies a Product! list of
field getters in order, passing each returned reference to the next, and wires inside
WithProvider, since it implements the foundational FieldGetter rather than the getter's own
provider trait. This chain reads a timeout through the context's configuration and connection:
use cgp::core::component::WithProvider;
use cgp::core::field::impls::ChainGetters;
delegate_components! {
App {
TimeoutGetterComponent: WithProvider<
ChainGetters<Product![
UseField<Symbol!("config")>, // App -> Config
UseField<Symbol!("connection")>, // Config -> Connection
UseField<Symbol!("timeout")>, // Connection -> Duration
]>,
>,
}
}
Each step is a FieldGetter provider, usually UseField, applied to the value the preceding step
returned. Wired without WithProvider, the chain fails the check with an unsatisfied
IsProviderFor<TimeoutGetterComponent, App>. ChainGetters is a zero-sized provider selected
through wiring, so the chain replaces a custom provider that would traverse the nested fields
manually.
Getters are just traits: explicit implementation
A getter can be implemented directly as an ordinary Rust trait. This is useful when the context
lacks HasField or stores the value under a different name. The macros generate access code, but
the consumer trait still supports a concrete impl:
pub struct Person {
pub full_name: String,
}
impl HasName for Person {
fn name(&self) -> &str {
&self.full_name
}
}
The direct impl requires only ordinary Rust trait knowledge. HasField, blanket impls, and getter
macros automate this access when useful.
Choosing between the constructs
Use #[implicit] by default when a provider reads its own context’s fields. This keeps the
dependency local and works even when several providers read the same field.
Use a getter trait for access on another type, a named accessor required by other code, or a
field-inferred associated type. Choose #[cgp_auto_getter] for fields matching the method name and
#[cgp_getter] with UseField when wiring must select the source field.
Use #[cgp_fn] for an operation with one implementation and a full component for
interchangeable providers. These forms can share the same field-access traits and rules.
Further reference
These online references describe the constructs as of CGP v0.8.0: