rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

empty_enum_variants_with_brackets is arguably not redundant

Open detly opened this issue 2 years ago • 4 comments

Description

I noticed that Clippy in Rust 1.77 includes a new lint empty_enum_variants_with_brackets (from #12047). The reasoning is that these are redundant.

Functionally, sure. But there is a feature of Rust where tuple-like enum variants get a kind of static function generated as a constructor for them, so you can do things like this:

pub enum Symbol {
    Number(i32),
    Text(String),
    Nothing(),
    Whitespace(),
}

pub fn parse_only_as_number(text: &str) -> Symbol {
    text.parse().ok().map_or_else(Symbol::Nothing, Symbol::Number)
}

This is extremely contrived, yes, but illustrates that (a) not every enum with empty variants will have a natural Default implementation, and (b) removing the () has effects outside of that change alone eg. any API requiring and receiving a FnOnce() -> Symbol now has to be called with a closure (|| Symbol::Nothing) or a static constructor has to be explicitly written.

I do not have strong feelings about it, but I do use this sometimes and I wanted to raise it in case it hadn't been considered. (Ideally I'd like Rust to extend the automatic static constructor thing to any empty-equivalent enum variant ie. Empty, Empty(), Empty(()) and Empty {} would all have it, but I'm not writing any RFCs any time soon.)

Version

rustc 1.77.0 (aedd173a2 2024-03-17)
binary: rustc
commit-hash: aedd173a2c086e558c2b66d3743b344f977621a7
commit-date: 2024-03-17
host: x86_64-unknown-linux-gnu
release: 1.77.0
LLVM version: 17.0.6

detly avatar Mar 25 '24 04:03 detly

Ideally I'd like Rust to extend the automatic static constructor thing to any empty-equivalent enum variant ie. Empty, Empty(), Empty(()) and Empty {}

Regarding this, https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/.E2.9C.94.20RFC.20idea/near/430262583 About the lint itself, the ideal solution would be to check if the variant is used as a function anywhere.

NullSpaceBoy avatar Apr 01 '24 14:04 NullSpaceBoy

About the lint itself, the ideal solution would be to check if the variant is used as a function anywhere.

What if it's pub?

detly avatar Apr 10 '24 17:04 detly

@rustbot claim

NullSpaceBoy avatar Jun 05 '24 04:06 NullSpaceBoy

Related Discussion: https://rust-lang.zulipchat.com/#narrow/stream/257328-clippy/topic/.60empty_enum_variants_with_brackets.60.20False.20Positive

NullSpaceBoy avatar Jun 05 '24 04:06 NullSpaceBoy