How to yield a Result if an iterator is not empty?

I am writing a parsing function that reads a custom text format. Each line should contains two f64 numbers separated by whitespace. The following code works.

#![feature(try_blocks)]
use anyhow::{Context, Result};

try {
    let mut iter = line.split_whitespace();
    let lat: f64 = iter.next()?.parse()?;
    let lon: f64 = iter.next()?.parse()?;

    // assert that there is no more items on that line
    assert_eq!(iter.next(), None, "{}", err_msg());
 
    output.insert(id, (lat, lon));
}.with_context(err_msg)?;

I would like to clean-up the try block to write something like

let err_msg = || format!("Invalid file format for {} line {}", filename, line_number);

try {
    let mut iter = line.split_whitespace();
    let lat: f64 = iter.next()?.parse()?;
    let lon: f64 = iter.next()?.parse()?;
    iter.next().is_none?;

    output.insert(id, (lat, lon));
}.with_context(err_msg)?;

Is there either a way to convert a bool to a result or a non-empty iterator to a result and then return with the try operator?

How about

iter.next().ok_or_else(|| your_error)?;

Hmm, it's backwards. You could do this I guess.

iter.next().xor(Some("")).ok_or_else(|| your_error)?;
2 Likes

Or be explicit.

if let Some(_) = iter.next() {
    return Err(your_err)
}
4 Likes

That's probably best.

Thanks all.

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