Skip to content

Suggest len instead of count on arrays, slices, or vectors #87302

Closed
@teor2345

Description

@teor2345

Given the following code:

fn main() {
    let slice = [1,2,3,4];
    let vec = vec![1,2,3,4];
    
    println!("{} {} {}", slice.count(), vec.count(), vec.as_slice().count());
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8bd1115b12adc0eb5feb16bbb63a06cb

The current output is:

error[E0599]: the method `count` exists for array `[{integer}; 4]`, but its trait bounds were not satisfied
 --> src/main.rs:5:32
  |
5 |     println!("{} {} {}", slice.count(), vec.count(), vec.as_slice().count());
  |                                ^^^^^ method cannot be called on `[{integer}; 4]` due to unsatisfied trait bounds
  |
  = note: the following trait bounds were not satisfied:
          `[{integer}; 4]: Iterator`
          which is required by `&mut [{integer}; 4]: Iterator`
          `[{integer}]: Iterator`
          which is required by `&mut [{integer}]: Iterator`

(repeated 3 times with slight variations)

Ideally the output should:

  • suggest using slice.len() instead of slice.count()

This is a common error, particularly for new users, and when switching between iterators and vectors/slices/arrays.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsD-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-papercutDiagnostics: An error or lint that needs small tweaks.T-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