Why does Split<String> have a last() method but not first()?

    let variable = expr_arg.split(" -> ").last().unwrap().to_string();
    let expr = Expression::new(expr_arg.split(" -> ").nth(0).unwrap());

It's equivalent to .next() or, as you observed, .nth(0), so there is no need for a differently named method with the same implementation, as it's trivial to implement. .last() would not be so trivial to implement: either you would need need to know the length of the iterator in advance (which is not possible without iterating over the entire string), or you would need to call .next() repeatedly. The dedicated .last() method saves you this piece of nontrivial logic.

Note that these are Iterator methods, available on all iterators. Also note that nth return elements relative to the current position in the iterator, not relative to the start of the iterator, hence nth(0) being the same as next.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.