Here's an example that splits a string and parses each item, putting it into a tuple whose size is known at compile time.
use std::str::FromStr;
fn main() {
let some_str = "123,321,312";
let num_pair_str = some_str.split(',').collect::<Vec<&str>>();
if num_pair_str.len() == 3 {
let num_pair: (i32, i32, i32) = (
i32::from_str(num_pair_str[0]).expect("failed to parse number"),
i32::from_str(num_pair_str[1]).expect("failed to parse number"),
i32::from_str(num_pair_str[2]).expect("failed to parse number"),
);
println!("Tuple {:?}", num_pair);
}
}
Is there a way to avoid repetition parsing the numbers?
This is an example of what it might look like if Rust supported Python-like comprehensions:
let num_pair: (i32, i32, i32) = (
i32::from_str(num_pair_str[i]).expect("failed to parse number")
for i in 0..3
);
Is it possible to declare the tuple in a way that expands the vector?