Chunks() in &str

Hi, I am trying to iterate over every two chars in &str by using chunks. But compile failed. Any suggestion? Thanks!
slice - Rust (

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\
3 |     for i in s.chunks(2) {
  |                ^^^^^^ method not found in `&str`

chunks is on &[T], not &str.

You might consider using Itertools::tuples:

for (a, b) in s.chars().tuples() {


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 =;
//... or 
let iter = slice.chunks_exact(2)


1 Like

@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.