How to perform lookaheads with string iterators?

52 Views Asked by At

I want to try to get familiar with Rust, so I'm attempting Crafting Interpreters. In the Longer Lexemes section it has a peek function that gets the character one ahead of the current index.

I'm not sure how to go about this in Rust. It seems that indexing strings is discouraged due to the design of the language and complexities with Unicode.

If I do chars.next() then it will consume the value. I thought that .as_bytes() on the original string could work, but that only supports ASCII values. From the internet, .chars().nth().unwrap() is the solution, but it seems to be very slow.

1

There are 1 best solutions below

0
suchislife On BEST ANSWER

A practical example of @BallpointBen's comment about using peekable would be:

fn main() {
    let data = "Hello, world!";
    let mut iter = data.chars().peekable();
    
    while let Some(&current) = iter.peek() {
        // Do something with the current character without consuming it
        println!("Current character: {}", current);

        // Now consume the character
        iter.next();
        
        // You can also peek the next character without consuming it
        if let Some(&next) = iter.peek() {
            println!("Next character: {}", next);
        } else {
            println!("This was the last character.");
        }
    }
}

Rust Playground Example

Output:

Current character: H
Next character: e
Current character: e
Next character: l
Current character: l
Next character: l
Current character: l
Next character: o
Current character: o
Next character: ,
Current character: ,
Next character:  
Current character:  
Next character: w
Current character: w
Next character: o
Current character: o
Next character: r
Current character: r
Next character: l
Current character: l
Next character: d
Current character: d
Next character: !