Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a list of numbers from a file into a Vec?

I'm trying to read in a list of numbers from a file (where each line has a number on it) into a Vec<i64> with Rust. I can get the numbers loaded from the file as strings using a BufReader. However, I can't seem to get the value of the strings out of the Result enum they are wrapped in by the BufReader.

So how does one get those values out of Result to parse, so they can populate a Vec with another type than strings?

What I have tried:

  1. Using a for loop where I can print the values to prove they're there, but it panics on the parse when I try to compile with the numbers.append(...) line.
fn load_from_file(file_path: &str) {
    let file = File::open(file_path).expect("file wasn't found.");
    let reader = BufReader::new(file);
    let numbers: Vec<i64> = Vec::new();

    for line in reader.lines() {
        // prints just fine
        println!("line: {:?}", line);
        numbers.append(line.unwrap().parse::<i64>());
    }
}
  1. Alternatively I tried mapping instead, but I encounter the same issue with getting the values into the Vec<i64> I'm trying to populate.
fn load_from_file(file_path: &str) {
    let file = File::open(file_path).expect("file wasn't found.");
    let reader = BufReader::new(file);

    let numbers: Vec<i64> = reader
        .lines()
        .map(|line| line.unwrap().parse::<i64>().collect());
}

This is not solved solely by How to do error handling in Rust and what are the common pitfalls?

like image 604
CoderLee Avatar asked Oct 27 '25 04:10

CoderLee


1 Answers

You can call the unwrap() method on Result enums to get values out of them. Fixed example:

use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;

fn load_from_file(file_path: &str) {
    let file = File::open(file_path).expect("file wasn't found.");
    let reader = BufReader::new(file);

    let numbers: Vec<i64> = reader
        .lines()
        .map(|line| line.unwrap().parse::<i64>().unwrap())
        .collect();
}

playground

like image 132
pretzelhammer Avatar answered Oct 29 '25 17:10

pretzelhammer



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!