Skip to main content

cgp_getter

Attribute Macro cgp_getter 

Source
#[cgp_getter]
Expand description

#[cgp_getter] is an extension to #[cgp_component] that derives additional getter constructs.

This macro can only be used on traits that contains only getter-like methods.

The macro accepts the same arguments as #[cgp_component], and generates the same CGP component constructs. Additionally, it also generates implementation for the following getter providers:

  • UseField<Tag> - implements the provider trait using HasField<Tag>.
  • UseFields - implements the provider trait using HasField, with the tag being the same name as the getter methods.
  • WithProvider<Provider> - implements the provider trait if the given Provider implements FieldGetter<ComponentName>.

§Example

Given the following getter component definition:

#[cgp_component(NameGetter)]
pub trait HasName {
    fn name(&self) -> &str;
}

The following getter providers are generated:

#[cgp_provider]
impl<Context, Tag> NameGetter<Context> for UseField<Tag>
where
    Context: HasField<Tag, Value = String>,
{
    fn get(context: &Context) -> &str {
        context.get_field(PhantomData).as_str()
    }
}

#[cgp_provider]
impl<Context> NameGetter<Context> for UseFields
where
    Context: HasField<symbol!("name"), Value = String>,
{
    fn get(context: &Context) -> &str {
        context.get_field(PhantomData).as_str()
    }
}

#[cgp_provider]
impl<Context, Provider> NameGetter<Context> for WithProvider<Provider>
where
    Provider: FieldGetter<Context, NameGetterComponent, Value = String>,
{
    fn get(context: &Context) -> &str {
        Provider::get_field(context, PhantomData).as_str()
    }
}