Split and nth()

When I split a string into two substrings and use nth(..) on the resulting plit iterator I get only one string back.

What I have done:

fn main() {
    let f = "first=2".to_string();
    let mut kv = f.split("=");
    println!("{:?}={:?}", kv.nth(0), kv.nth(1));
}

The result is:

cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `/home/worik/tmp/sandbox/target/debug/sandbox`
Some("first")=None

Why do I not see the second string? (Some"2")

1 Like

nth mutates the iterator, consuming all items up to and including the nth. (that's the only thing it can do, given that an iterator is defined as a type with a function fn next(&mut self) -> Option<Item>).

fn main() {
    let f = "first=2".to_string();
    let mut kv = f.split("=");
    println!("{:?}={:?}", kv.nth(0), kv.nth(0));
}
Some("first")=Some("2")

Many iterators are clonable, in case you need to be able to return to a previous state:

fn main() {
    let f = "first=2".to_string();
    let mut kv = f.split("=");
    println!("{:?}={:?}", kv.clone().nth(0), kv.nth(1));
}

I read that in the documentation. But when I call nth(0) that consumes item 0. Why can I not then access item 1 with nth(1)?

When you consume the 0th item, item 1 becomes the new 0th item.

3 Likes

Are yes. Thank you

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.