Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Severity trait & fix wildcard enum foot gun #207

Merged
merged 1 commit into from
May 2, 2024
Merged

Conversation

ajjahn
Copy link
Contributor

@ajjahn ajjahn commented May 2, 2024

No description provided.

// but not added to the match expression.
#[allow(dead_code)]
fn ensure_all_variants_handled(variant: Self) {
use LambdaRequestError::*;
Copy link
Contributor Author

@ajjahn ajjahn May 2, 2024

Choose a reason for hiding this comment

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

Wildcard using the variants in an enum can be a gotcha. If someone were to remove a variant from the enum, the following match statement wouldn't catch it. Instead the variant that was removed would become a variable declaration for a catchall branch of the match. Like using a _.

@@ -166,46 +135,46 @@ mod tests {

#[test]
fn test_worse() {
use LambdaRequestError::*;
use LambdaRequestError as E;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

If an enum has many variants and you want to avoid typing the name repeatedly, it is safer to use ... as to ensure the problem above can't happen.

Self::RouterConnectionError => 2,
Self::AppConnectionUnreachable => 3,
Self::AppConnectionError => 4,
Self::ChannelErrorOther => 5,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Since the test ensuring all members are added to the ordered array had to list all members in a match, we may as well explicitly assign them a severity.

Another option would be to define the variants in order when defining the enum. Then you can cast the enum into a usize and compare them. But that also is easy to break by reordering the variant definitions or defining a new one in the wrong place.

Copy link
Contributor

@huntharo huntharo left a comment

Choose a reason for hiding this comment

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

Thanks for the fix!

@huntharo huntharo merged commit 7f82820 into pwrdrvr:main May 2, 2024
10 checks passed
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.

None yet

2 participants