Jaebum
Jaebum

Reputation: 1570

Why can I not `.iter()` a string slice?

Why iterating over the string slice is not possible?

fn main() {
    let text = "abcd";
    for (i, c) in text.iter().enumerate() {
        // ...
    } 
}

gives an error

error[E0599]: no method named `iter` found for reference `&str` in the current scope
 --> src/main.rs:3:24
  |
3 |     for (i, c) in text.iter().enumerate() {
  |                        ^^^^ method not found in `&str`

How do I make the string slice iterable?

Upvotes: 4

Views: 2350

Answers (2)

kmdreko
kmdreko

Reputation: 60493

There is no .iter() method defined for str; perhaps because it is potentially ambiguous. Even in your question, its not clear what exactly you want to iterate over, the characters or the bytes.

  • .bytes() will yield the raw utf-8 encoded bytes
  • .chars() will yield the chars, which are unicode scalar values
  • or maybe .graphemes() from the unicode-segmentation crate which yields substrings for each "user-perceived character"

There are plenty of use-cases for each, just choose which is most appropriate. Playground

use unicode_segmentation::UnicodeSegmentation; // 1.8.0

fn main() {
    let text = "🤦🏼‍♂️"; // browser rendering may vary
    println!("{}", text.bytes().count());         // 17
    println!("{}", text.chars().count());         // 5
    println!("{}", text.graphemes(true).count()); // 1
}

Upvotes: 21

Joël Hecht
Joël Hecht

Reputation: 1842

To iterate on a string chars, you can use the chars() method:

fn main() {
    let text = "abcd";
    for (i, c) in text.chars().enumerate() {
       println!("i={} c={}", i, c) 
    } 
}

Upvotes: 0

Related Questions