Hi, I am trying to iterate over every two chars in &str by using chunks. But compile failed. Any suggestion? Thanks! slice - Rust (rust-lang.org)
fn main() {
let s = "abcdefg";
for i in s.chunks(2) {
}
}
error[E0599]: no method named `chunks` found for reference `&str` in the current scope
--> src\main.rs:3:16
|
3 | for i in s.chunks(2) {
| ^^^^^^ method not found in `&str`
If you convert the string into a slice (likely by not instantiating the input to String in the first place), you could opt for something such as the following:
let iter = slice.windows(2).step_by(2);
//... or
let iter = slice.chunks_exact(2)
@EdmundsEcho&[char] is generally not a type you want to be working with, and I find it hard to imagine where it would naturally come up (note that you can already collect an iterator of char into a String).
I agree; using chars is awkward and generally unnecessary. However, perhaps in this case, parsing a string, we need the char view of the world to accomplish the task. Note how it avoids using an external lib.