Skip to content

Conversation

@kiendang
Copy link
Contributor

@kiendang kiendang commented Jun 25, 2025

Resolves #388

Synopsis

Add Deref and DerefMut derive for enums. Only works on a single field of each variant of the enum and as long as the field types are compatible.

#[derive(Deref)]
enum NumRefEnum3 {
    Variant1 {
        #[deref(forward)]
        num: Box<i32>,
        useless: bool,
    },
    Variant2 {
        num: i32,
        #[deref(ignore)]
        useless: bool,
    },
    Variant3(i32),
}

See added docs and tests for more usage examples.

Solution

Make sure each of the enum variants contains 1 and only 1 enabled field, then generate a match block to extract the field. Checking if the field types are compatible are unnecessary since this case will fail compilation anyway.

Checklist

  • Documentation is updated (if required)
  • Tests are added/updated (if required)
  • CHANGELOG entry is added (if required)

@kiendang
Copy link
Contributor Author

The failed lints are unrelated. Fixed in #486.

@tyranron tyranron added this to the 2.1.0 milestone Jun 25, 2025
@tyranron tyranron self-requested a review June 25, 2025 17:14
Copy link
Collaborator

@tyranron tyranron left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kiendang thanks!

@tyranron tyranron merged commit c2b1a62 into JelteF:master Jul 7, 2025
17 checks passed
@kiendang kiendang deleted the deref-enum branch July 7, 2025 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Deref and DerefMut for enums

2 participants