Splitting array into variables


#1

I’m reading lines from a file. Each line looks like this 1 2 3 4 5 6\n and I want each value assigned to a variable like this: x = 1, y = 2, z = 3 and so on. They need to be converted to i32, so I could easily operate with them.

To rephrase in a programming language, here’s an example in Python:

x, y, z, a, b, c = map(int, '1 2 3 4 5 6\n'.split())

So far here’s what I came up with in Rust:

let split_line: Vec<&str> = "1 2 3 4 5 6\n".trim().split(" ").collect();
let x: i32 = split_line[0].parse().unwrap();
let y: i32 = split_line[1].parse().unwrap();
let z: i32 = split_line[2].parse().unwrap();
let a: i32 = split_line[3].parse().unwrap();
let b: i32 = split_line[4].parse().unwrap();
let c: i32 = split_line[5].parse().unwrap();

Is there any way of making this more concise (preferably without writing a macro, which I am aware is possible, but which would make it longer and more obscure)?


#2

not in stable rust. Any reason why they need to be their own variables? Would the following solve your issue, since you’d then have a vector of i32?

let v: Vec<i32> = "1 2 3 4 5 6\n"
    .trim()
    .split(" ")
    .map(|val| val.parse().unwrap())
    .collect();

if you then need them as their own variable, you can destructure a temporary tuple

let (x, y, z, a, b, c) = (v[0], v[1], v[2], v[3], v[4], v[5]);

#3

Thanks @oli_obk. I haven’t thought of destructuring a temporary tuple, I still hoped there would be something similar to to_tuple (although I couldn’t find it in docs). I wonder if a method like this would make sense or be useful to others.

Regarding the variables vs array indices – I store them in their own variables for readability reasons mostly. In reality they’re not actually x, y, z etc. but rather variables with longer meaningful names.

Edit: I also thought that since "1".parse().unwrap() automatically determines the type to parse into (i32 in this case), then it would be possible to have x, y, z, a, b, c with different types (e.g. x: i32, y: f64 etc.), however this doesn’t work:

let (x: i32, y: i64) = (1, 2);

#4

Yea, without macros you are not going to get this code more readable.

You can still define a tuple with multiple types, but if you have long names and expressions, the one let statement per line method is much more readable.

let (x, y): (i32, i64) = (1, 2);