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?