Skip to content

Allow abstract types to be defined in #[cgp_getter] #183

@soareschen

Description

@soareschen

Problem Statement

Currently, #[cgp_getter] and #[cgp_auto_getter] does not support abstract types to be defined in the getter trait. However, abstract types are often useful if we don't care about the concrete field type, but rather that the field type implements a certain trait.

Support for abstract types

We will add support for abstract types in #[cgp_auto_getter] with the following syntax:

#[cgp_auto_getter]
pub trait HasName {
    #[use_field(name)]
    type Name: Display;

    fn name(&self) -> &Self::Name;
}

If the getter trait only contains one field, the #[use_field(...)] attribute can be omitted. But we leave it here for illustrative purpose.

The above code will generate blanket implementation that binds the Name type to the type in the name field:

impl<Context, Name> HasName for Context
where
    Context: HasField<Symbol!("name"), Value = Name>,
    Name: Display,
{
    type Name = Name;

    fn name(&self) -> &Name {
        self.get_field(PhantomData)
    }
}

Embedding in #[cgp_impl]

Similar to #181, the abstract field types can be embedded inside #[cgp_auto_impl] and #[cgp_impl] with the same style as the getter methods. For example:

#[cgp_auto_impl]
pub trait CanGreet {
    #[use_field(name)]
    type Name: Display;

    #[getter]
    fn name(&self) -> &Self::Name;

    fn greet(&self) {
        println!("Hello, {}", self.name());
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions