Skip to content

Confusing error messages (a closure can't be cloned) #37736

Closed
@gibfahn

Description

@gibfahn

Trying to filter and then clone an Iterator over the chars in &str, I'm getting an error message that was pretty opaque (at least to me).

Code

    let f = |c: &char| c.is_digit(10);
    let iter = "abc123".chars().filter(f);
    match iter.clone().take(3).count() {
        3 => println!("{}", iter.collect::<String>()), // Print whole string including first three digits
        _ => {},
    }

Error

error: no method named `clone` found for type `std::iter::Filter<std::str::Chars<'_>, [closure@test.rs:2:13: 2:38]>` in the current scope
 --> test.rs:4:16
  |
4 |     match iter.clone().take(3).count() {
  |                ^^^^^
  |
  = note: the method `clone` exists but the following trait bounds were not satisfied: `[closure@test.rs:2:13: 2:38] : std::clone::Clone`

error: aborting due to previous error

It'd be nice if this error gave more info about how to fix the problem (the fix seems to be to change L1 from let f = |c: &char| to let f = &|c: &char|).

Sorry if this is a duplicate, I couldn't find anything obvious.

EDIT: What I'm trying to do is to make sure there are at least three digits in my Iterator before I actually collect it, I suspect the right answer isn't changing the filter closure (I'm not sure why that fixes the compiler error tbh), but using something else instead of iter.clone().

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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