I am trying to parse the buf to get the numbers out while accounting for parsing errors.
What is the best way of iterating over vector and matching.
I were able to compile the following solutions
let buf = "32X42X52";
let mut result: Vec<_> = buf.split('X').map(|n| n.parse::<u32>()).collect();
// Version 1
for (i, ref item) in result.iter().enumerate() {
match **item {
Ok(n) => { /* use i and n */ },
Err(ref ParseIntError) => return Err("Bad string".to_owned()),
}
}
// Version 2
for (i, item) in result.iter().enumerate() {
match item {
&Ok(n) => { /* use i and n */ },
&Err(ref ParseIntError) => return Err("Bad size in gift sizes".to_owned()),
}
}
And also is there a way of dropping Err variants before .collect() call in the chain?
It is debugging output though. I expect that some of the iterators will have their debug output made much prettier, for example the Chars iterator should show the string of course and so on.
I don't expect you will ever see the output you desire, because there is a closure the debugging code can't call inbetween (it doesn't know how sideeffectful it might be). But the parts that have no side effects, like the string splitting, can all be computed in Debug.
It could be OK as long as the function is in the Prelude... But there's another bigger problem. If I print 20 MB of text of an iterable, I don't want to allocate in memory the whole iterable. I'd like to print it on a file in a lazy way (this is what D language does with its ranges. You don't need to convert them to arrays before printing them).
By the way, I think use std::iter::FromIterator and Vec::from_iter(...) is a nicer more explicit way to do the same collect operation. Less punctuation to type, too.
This is a slight different topic. I think the std library needs something like a "to_vec()" function that works with iterables, because converting iterables to vectors is a quite common operation in Rust.