rust-lang / rust-lang/rust-clippy

clippy::large_enum_variant should suggest Option<Box<T>> over Box<Option<T>>

Open
#9,983 3 comments 2 reactions 1 assignee View on GitHub

@Centri3 is already working on this.

Since Jun 15, 2023.

C-enhancement L-suggestion
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Description

Consider this example:

struct LargeValue([u8; 201]);

enum Foo {
    Large(Option<LargeValue>),
    Small,
}

Running cargo clippy gives this warning:

warning: large size difference between variants
 --> src/lib.rs:3:1
  |
3 | / enum Foo {
4 | |     Large(Option<LargeValue>),
  | |     ------------------------- the largest variant contains at least 202 bytes
5 | |     Small,
  | |     ----- the second-largest variant carries no data at all
6 | | }
  | |_^ the entire enum is at least 202 bytes
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#large_enum_variant
  = note: `#[warn(clippy::large_enum_variant)]` on by default
help: consider boxing the large fields to reduce the total size of the enum
  |
4 |     Large(Box<Option<LargeValue>>),
  |           ~~~~~~~~~~~~~~~~~~~~~~~

Boxing an option is inefficient in the case of None, since it still needs to allocate the None on the heap and it can't take advantage of null pointer optimization. Instead, the lint should suggest Option<Box<LargeValue>> when the original field is Option<LargeValue>.

Version
rustc 1.67.0-nightly (a28f3c88e 2022-11-20)
binary: rustc
commit-hash: a28f3c88e50a77bc2a91889241248c4543854e61
commit-date: 2022-11-20
host: x86_64-apple-darwin
release: 1.67.0-nightly
LLVM version: 15.0.4
Additional Labels

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.