Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify parsing a text file to a vector of values?

Tags:

rust

I'm new to Rust and I'm trying to find the most simple and effective way of parsing text file like:

1
2
3
4
5

to a vector of u32 in my code. For now I have a solution for reading a file as string (it's just right from rustbyexample.com, I changed it a little):

let path = Path::new("J:/IntegerArray.txt");
let display = path.display();

let mut file = match File::open(&path)
{
    Err(why) => panic!("couldn't open {}: {}", display, why.desc),
    Ok(file) => file,
};

let data_str = match file.read_to_string()
{
    Err(why) => panic!("couldn't read {}: {}", display, why.desc),
    Ok(string) =>
    {
        string
    }
};

Then I parse it:

let mut data : Vec<u32> = vec![];

for str in data_str.lines_any()
{
    data.push(match str.trim().parse() { Some(x) => x, None => continue, } );
}

However I think there's a solution where it could be done in one line without a loop, something like:

let mut data : Vec<u32> = data_str.lines_any().<SOME MAGIC>.collect();

Maybe it can be done with map and filter, but the main problem is in unwrapping Option to u32, because I can't see how to filter away Nones and unwrap to u32 at the same time. Otherwise, just filtering without unwrapping leads to checking for them again further. Is a one-line solution possible? And will it be an effective solution?

like image 342
Arsenii Fomin Avatar asked Oct 15 '25 09:10

Arsenii Fomin


1 Answers

filter_map is what you're looking for:

let data: Vec<u32> = data_str.lines_any().filter_map(|s| s.trim().parse()).collect();
like image 118
Ray Avatar answered Oct 18 '25 10:10

Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!