Skip to content

Literal &[char] patterns clumsily require an as conversion #39511

Closed
@jimblandy

Description

@jimblandy

Many str methods accept patterns of any type that implements the std::str::pattern::Pattern trait. One such type is &[char], which matches any single character mentioned in the pattern slice.

However, &[char] patterns are not as nice to use as one might hope. This does not compile:

        let code = "\t    function noodle() { ";
        assert_eq!(code.trim_left_matches(&[' ', '\t']),
                   "function noodle() { ");

Rust complains:

error[E0277]: the trait bound `[char; 2]: std::ops::Fn<(char,)>` is not satisfied
   --> lib.rs:689:29
    |
689 |             assert_eq!(code.trim_left_matches(&[' ', '\t']),
    |                             ^^^^^^^^^^^^^^^^^ the trait `std::ops::Fn<(char,)>` is not implemented for `[char; 2]`
    |
    = note: required because of the requirements on the impl of `std::ops::FnOnce<(char,)>` for `&[char; 2]`
    = note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `&[char; 2]`

The trim_left_matches method constrains its argument type P with P: Pattern, and Rust won't apply the usual type coercions like &[T; N] to &[T] in order to satisfy trait bounds.

One must instead write:

            let code = "\t    function noodle() { ";
            assert_eq!(code.trim_left_matches(&[' ', '\t'] as &[char]),
                       "function noodle() { ");

It's not a tragedy, but it's not pretty either.

CC @alexcrichton

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions