Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>)?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading