Skip to content

Error message for private method of Option<T> is suboptimal #143795

Open
@tdittr

Description

@tdittr

Code

fn main() {
    let maybe_vec = Some(vec![1,2,3]);
    assert_eq!(maybe_vec.len(), 3);
}

Current output

error[E0624]: method `len` is private
   --> src/main.rs:3:26
    |
3   |     assert_eq!(maybe_vec.len(), 3);
    |                          ^^^ private method
    |
   ::: /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/option.rs:800:5
    |
800 |     const fn len(&self) -> usize {
    |     ---------------------------- private method defined here

For more information about this error, try `rustc --explain E0624`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Desired output

error[E0599]: no method named `len` found for enum `Option` in the current scope
    --> src/main.rs:3:26
     |
3    |     assert_eq!(maybe_vec.len(), 3);
     |                          ^^^^^^^^ method not found in `Option<Vec<{integer}>>`
     |
note: the method `len` exists on the type `Vec<{integer}>`
    --> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:1303:5
     |
1303 |     pub const fn len(&self) -> usize {
     |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: consider using `Option::expect` to unwrap the `Vec<{integer}>` value, panicking if the value is an `Option::None`
     |
3    |     assert_eq!(maybe_vec.expect("REASON").len(), 3);
     |                         +++++++++++++++++

For more information about this error, try `rustc --explain E0599`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Rationale and extra context

When a method that is present on the inner type of an Option<T> is called, the compiler gives nice feedback on unwrapping the option in order to access that method.

However Option::len does exist, but is private. So in that case the error message is less useful. Compare that with the output of this example which matches with the "Desired Output" above:

fn main() {
    let maybe_vec = Some(vec![1,2,3]);
    assert_eq!(maybe_vec.capacity(), 3);
}

Other cases

Rust Version

Build using the Nightly version: 1.90.0-nightly

(2025-07-10 2a023bf80a6fbd6a06d5)

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions