Skip to content

Support associated type in getter trait#191

Merged
soareschen merged 11 commits intomainfrom
getter-type
Feb 1, 2026
Merged

Support associated type in getter trait#191
soareschen merged 11 commits intomainfrom
getter-type

Conversation

@soareschen
Copy link
Collaborator

@soareschen soareschen commented Feb 1, 2026

Summary

This PR adds support to define getter traits with abstract field types through a local associated type. For example, one can now define an auto getter trait like follows:

#[cgp_auto_getter]
pub trait HasName {
    type Name: Display;

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

The HasName trait now has an abstract Name type that is automatically derived from the name field in a struct. With that, given a struct like:

#[derive(HasField)]
pub struct Person {
    pub name: String,
}

The HasName trait would be automatically implemented with String as the Name type.

Benefits

The main benefit of this is that it becomes much less tedious to define getter methods containing types that we don't care. Without it, we would need to also define an abstract type trait, which does not support auto derivation:

#[cgp_type]
pub trait HasNameType {
    type Name: Display;
}

#[cgp_auto_getter]
pub trait HasName {
    fn name(&self) -> &Self::Name;
}

This is significantly more tedious, and discourages users from defining the getter field with abstract types.

Use with #[cgp_getter]

The abstract field type can also be used with #[cgp_getter], such as:

#[cgp_getter]
pub trait HasName {
    type Name: Display;

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

With that, the getter trait may be implemented through UseField as usual:

#[derive(HasField)]
pub struct Person {
    pub first_name: String,
}

delegate_components! {
    Person {
        NameGetterComponent:
            UseField<Symbol!("first_name")>,
    }
}

Limitation

Abstract types in getter traits can only be used when there is exactly one getter method. Additionally, the return type must precisely match the associated type, modulo the modifiers like & and &mut. e.g. you can't define a getter like fn optional_name(&self) -> Option<&Self::Name>.

@soareschen soareschen merged commit ac96b72 into main Feb 1, 2026
5 checks passed
@soareschen soareschen deleted the getter-type branch February 1, 2026 18:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant