Unpack BufReader line into variables of different data types

Budding Rustacean here. I have a BufReader iterator for a file, where each line is of the form
string int

I also have string_var: &str and int_var: i32 variables into which I would like to unwrap the contents of this line. You may assume each line always contains two strings separated by a space.

Given this assumption, I'm looking for an idiomatic way to achieve my goal (ideally by chaining a series of methods to extract the string and int from the each string line). My code looks something like this:

for line in file_iterator.lines() {
    (string_var, int_var) = line.unwrap().<insert_cool_rust_methods_I_dont_know_yet>
    // use string_var and int_var for useful computations
}
for line in file_iterator.lines() {
    let line = line.unwrap();
    let mut split = line.split();
    let string_var = split.next().unwrap();
    let int_var: i32 = split.next().unwrap().parse().unwrap();

    // use string_var and int_var for useful computations
}
1 Like

Thanks @alice ! Any chance there's a way to somehow map two values in a line into a string and an int by using map() and closures (or some other sequence of chained commands in one line)?

Something like

(string_var, int_var) = line.unwrap().split().map(|(string1, string2)| => (string1, string2.parse())).<insert_some_idiomatic_chain_of_rust_methods>

I'm just trying to see if there are more clean alternatives to achieving my goal.

So this is what I ended up finding:

let (direction, magnitude) = line.split_once(" ").map(|(d, m)| {
    (d, m.parse::<i32>().unwrap())
}).unwrap();

If anyone thinks this isn't the right way of going about getting the result I need, I would be more than happy to correct my ways. Thanks!

I've never heard of split_once. It's very new apparently.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.