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
Many
strmethods accept patterns of any type that implements thestd::str::pattern::Patterntrait. 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:Rust complains:
The
trim_left_matchesmethod constrains its argument typePwithP: 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:
It's not a tragedy, but it's not pretty either.
CC @alexcrichton