#[cgp_getter]
Define a getter as a full component, so the field it reads is chosen by wiring rather than by its name.
Overview
In Context-Generic Programming (CGP), #[cgp_auto_getter] ties a
getter to a field of the same name: declare
fn name(&self) -> &str and every context with a name field satisfies it. That is the right tradeoff almost
always, and it has one hard limitation: a context that stores the value under a different name cannot use the
getter at all.
#[cgp_getter] removes that coupling by making the getter a real component. The context is the
type the method runs on, and it supplies the values it needs as its own fields. It then says
in its wiring which field the getter should read:
delegate_components! {
Person {
NameGetterComponent: UseField<Symbol!("first_name")>,
}
}
Person::name() now returns the first_name field. The method is still called name; the field it reads
has moved into the wiring, where a context can change it without touching the trait or any code that calls
it.
This is an advanced tool, not the next step up from #[cgp_auto_getter]. The decoupling costs a
line of wiring per context, and it helps only when a context needs
to control which field is read, or to supply the value some way other than reading a field. Most getters
need neither. The When to use it section draws the line.
Usage
Apply the attribute to a getter trait, exactly as with #[cgp_auto_getter]. It
accepts the same method forms: every receiver shape, including a
typed reference to another type in place of
self and an optional PhantomData argument;
and the &str, &[T], Option<&T>, Option<&str>, MRef<'_, T>, owned, and associated-type return
shorthands, with their access rules
unchanged. The two macros share one parser, so a method the one accepts the other does too:
#[cgp_getter]
pub trait HasName {
fn name(&self) -> &str;
}
Because #[cgp_getter] builds on #[cgp_component], it needs a provider
trait name and derives one from the trait name: a leading Has is stripped and Getter
appended, so HasName yields the provider trait NameGetter and the marker NameGetterComponent.
The macro is therefore at its most ergonomic when getter traits follow the Has{Field} convention.
A trait whose name does not start with Has, or is exactly Has, gets no default, and must name
its provider.
Pass an identifier to override it, as with #[cgp_component]:
#[cgp_getter(GetName)]
pub trait HasName {
fn name(&self) -> &str;
}
Here the provider trait is GetName and the component GetNameComponent. The keyed
name / provider / context form works too; only the default for provider differs from
#[cgp_component].
The companion attributes of #[cgp_component] apply here too, so
#[prefix(...)] registers the getter into a namespace.
What a context can wire it to
The macro produces these providers, and which you name decides where the value comes from:
| Wire it to | The getter reads |
|---|---|
UseField<Symbol!("f")> | the field named f, whatever the method is called |
UseFields | the field named after each method, the #[cgp_auto_getter] behaviour as a provider |
WithProvider<P> | whatever the field-getter provider P supplies |
UseField is the one to use, and the reason the construct exists. UseFields is useful when a
trait has several methods and the names all happen to match, and it is the only one of them that
works for a multi-method trait: the other two presuppose a single field.
A #[cgp_getter] trait can also be implemented directly on a concrete context, like any Rust trait, when
a particular context wants neither wiring nor a field.
Examples
The case #[cgp_auto_getter] cannot express: the trait method is name, and the context stores the value
in first_name.
use cgp::core::field::impls::UseField;
use cgp::prelude::*;
#[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")>,
}
}
check_components! {
Person {
NameGetterComponent,
}
}
pub fn greet(person: &Person) {
println!("Hello, {}!", person.name());
}
person.name() returns first_name, because the wiring said so. A second context can store it under yet
another name and wire accordingly, with HasName and every caller unchanged. This is the whole
difference from the blanket-impl getter. Person is a
value context here, the person whose name is read.
Where the names do line up, UseFields gives the auto-getter behaviour without giving up the component:
#[derive(HasField)]
pub struct Employee {
pub name: String,
}
delegate_components! {
Employee {
NameGetterComponent: UseFields,
}
}
And a context that computes the value rather than storing it implements the consumer trait directly, skipping both the wiring and the field:
pub struct Anonymous;
impl HasName for Anonymous {
fn name(&self) -> &str {
"anonymous"
}
}
That last form is worth seeing, because it shows a #[cgp_getter] trait is an ordinary component whose
consumer trait can be implemented like any Rust trait.
When to use it
Do not use #[cgp_getter] by default. Among the ways to read a value from a context it is
the last resort, and the ordering is worth keeping whole:
- An
#[implicit]argument for a provider reading a field of its own context. No trait, no wiring. This covers most reads. #[cgp_auto_getter]when the accessor has to exist as a named trait other code depends on, when the field lives on another type, or when the getter carries a type inferred from the field. One blanket impl, still no wiring.#[cgp_getter]only when a context must control how the getter is satisfied.
That third condition is narrow, and it has two real forms. One is a field name that differs per
context: the same trait reading first_name on one type and display_name on another. The other
is a context that supplies the value some way other than a plain field read, through
WithProvider or a hand-written impl, while other contexts still read a field.
Use something else in these cases.
- Every context stores the field under the method's name. Then the wiring line is pure overhead:
#[cgp_auto_getter]gives the same result with nothing to wire, and wiringUseFieldshere is a sign the component was not needed. - Only one provider reads the value. An
#[implicit]argument is shorter and keeps the requirement where the provider is written. - The value is a type rather than a value.
#[cgp_type]is the abstract-type component, andUseTypeis its counterpart to this construct'sUseField. - The trait has several methods and you want per-context field choice for each.
UseFieldhandles one field, so a multi-method getter wired this way has to go throughUseFieldsor a hand-written provider. Splitting into one component per field is usually the better answer.
Under the hood
#[cgp_getter] emits everything #[cgp_component] would: the consumer trait,
the provider trait, the two blanket impls, the marker, and the standard
UseContext and RedirectLookup
impls. It then adds the getter providers below, in the order UseFields, UseField,
WithProvider. The macro always emits UseFields; it emits UseField and WithProvider only when
the trait has exactly one method, since both presuppose a single field.
The important addition is the UseField impl, which decouples the field from the method name.
From this trait:
#[cgp_getter]
pub trait HasName {
fn name(&self) -> &str;
}
the macro generates:
impl<__Context__, __Tag__> NameGetter<__Context__> for UseField<__Tag__>
where
__Context__: HasField<__Tag__, Value = String>,
{
fn name(__context__: &__Context__) -> &str {
__context__.get_field(PhantomData::<__Tag__>).as_ref()
}
}
__Tag__ is a free generic parameter, and that is the entire difference from
#[cgp_auto_getter], whose blanket impl hard-codes the tag to
Symbol!("name"). Here the tag is whatever the wiring supplies, so UseField<Symbol!("first_name")>
reads first_name. The &str shorthand behaves identically in both: the bound asks for a String and the
body appends .as_ref().
Next is the UseFields impl, which is the auto-getter's behaviour expressed as a provider, with the
tag fixed to each method's own name:
impl<__Context__> NameGetter<__Context__> for UseFields
where
__Context__: HasField<Symbol!("name"), Value = String>,
{
fn name(__context__: &__Context__) -> &str {
__context__.get_field(PhantomData::<Symbol!("name")>).as_ref()
}
}
Last is a WithProvider impl, which adapts a general field-getter
provider into this component, so the value need not come from a field read at all:
impl<__Context__, __Provider__> NameGetter<__Context__> for WithProvider<__Provider__>
where
__Provider__: FieldGetter<__Context__, NameGetterComponent, Value = String>,
{
fn name(__context__: &__Context__) -> &str {
__Provider__::get_field(__context__, PhantomData::<NameGetterComponent>).as_ref()
}
}
The WithProvider bound follows the getter's shape. A &mut self getter bounds on
MutFieldGetter instead of FieldGetter and reads through get_field_mut, and a slice getter
returning &[T] bounds the value as Value: AsRef<[T]> + 'static rather than fixing it with
Value =. The UseField and UseFields bounds change the same way, to HasFieldMut and to the
AsRef bound.
Each of these is paired with a matching IsProviderFor impl carrying the
same bounds, so a missing field is reported by name when the component is checked.
Formal grammar
The attribute argument is the same grammar as #[cgp_component]'s, in the Rust
Reference's notation:
CgpGetterArgs -> CgpComponentArgs // see #[cgp_component]
A bare provider name, or the keyed name / provider / context form. The only difference from
#[cgp_component] is the default applied when provider is omitted: rather than being required, it is
derived from the trait name by stripping a leading Has and appending Getter, so HasName yields
NameGetter. Every other key and default behaves as documented there.
Common Mistakes
A multi-method trait gets no UseField provider. Both UseField and WithProvider are emitted only
for a single-method trait, because each supplies one field. Wiring a two-method getter to
UseField<Symbol!("width")> therefore reports the provider as not being a provider for the component,
with the tag expanded into its raw list:
error[E0277]: the trait bound `UseField<cgp::macro_prelude::Symbol<5, cgp::macro_prelude::Chars<'w', …>>>: IsProviderFor<DimensionsGetterComponent, Rectangle>` is not satisfied
Nothing in that says the trait had too many methods, which is the actual cause. Use UseFields, or split
the trait into one component per field.
A trait not named Has… must name its provider. The default comes from stripping a leading
Has, so a trait such as Dimensions has nothing to strip, and a bare #[cgp_getter] on it fails:
error: the `provider` key must be given
Pass the provider name, as in #[cgp_getter(DimensionsGetter)].
Wiring UseFields everywhere means the component was unnecessary. If no context ever names a
different field, #[cgp_auto_getter] does the same job with no wiring at all, and
the component is a line per context of pure overhead.
The field's type still has to match the return type's rule. UseField<Symbol!("first_name")> on a getter
returning &str requires first_name to be a String; a &'static str field does not qualify, because the
tag chose the field and not the conversion:
error[E0271]: type mismatch resolving `<Person as HasField<Symbol<10, Chars<'f', …>>>>::Value == String`
The Symbol<10, …> in that message is first_name with its length in bytes, worth being able to read
since the tag tells you which field the mismatch is about.
A &mut self getter cannot return a shared Option, and Option<&[T]> is unsupported. Both
come from the method parsing this macro shares with #[cgp_auto_getter], which documents them under
Common Mistakes: the first fails with E0308 in every
generated provider, and the macro rejects the second.
Related constructs
#[cgp_auto_getter]— the blanket-impl getter, and the one to prefer.#[implicit]— the default way to read a field, ahead of either getter.UseField— the provider that makes the field name a wiring decision, withUseFieldRefandUseFieldsalongside it.#[cgp_component]— the macro this extends, and the source of the naming rules.#[derive(HasField)]andHasField— the field access underneath.Symbol!— the type-level field name a wiring entry supplies.WithProvider— the adapter for a value that does not come from a field.#[cgp_type]— the same idea for a type rather than a value.
The ideas behind it:
- Implicit arguments — the default way to read a field, and why this is the advanced fallback.
Source
- Entry point:
cgp_getter.rs - Implementation:
types/cgp_getter/ - Getter parsing, shared with
#[cgp_auto_getter]:functions/getter/parse.rs
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.