Parse a tuple of strings to usize

What is the idiomatic way of parsing ("5", "6") to (5, 6)? I have already tried calling .map(String::parse::<usize>) but that doesn’t work because tuples are not iterators. Nor can I call .into_iter().

>Solution :

Tuples are meant to be heterogeneous collections and as such you can’t really iterate over them, as different elements can, in principle, have different types.

So the easiest way is just

let a: usize = my_tuple.0.parse()?;
let b: usize = my_tuple.1.parse()?;

and if you need something more "sophisticated" you’ll have to use a macro:
How to iterate or map over tuples?

This might seem unnecessarily cumbersome when you compare it with Python, where tuples are indeed iterable. But that’s because you have dynamic and duck typing in Python, so the fact that tuples can be heterogeneous (different datatypes in different positions) isn’t that big of a deal.

Think about it. What would even the signature be for the closure to pass to map in a tuple of type, say, (i32, String, Option<f64>)?

Leave a Reply