Reading .txt file into HashMap

Viewed 60

I have a simple text file:

test.txt

my_email@domain.com
my_password

I would like to read each of these lines into a HashMap that is structured like:

use std::collections::HashMap;
use std::fs:File;
use std::io::BufReader;

fn main() -> Result<(), std::io::Error>
{
    let file = File::open("test.txt")
                    .expect("Cant open the file. Check the path");
    let buf_reader = BufReader::new(file);
    
    // Now I need to extract the lines and place them in my hashmap appropriately.
    // I was trying to read lines (just for testing) using:
    // for line in buf_reader.lines()
    // { 
    //     println!("{}", line?);
    // }
    //  But not sure if there is a better way to extract 0th and 1st // index from the .lines()


    let my_map = HashMap::from([
        ("email", // Want my first line of test.txt to be here),
        ("pw", // want my second line of text.txt to be here)
    ]);
}

Edit I Think I figured out the line? error. I needed to annotate my main() result But regardless, would appreciate optimal way to perform the above operation. Read lines into maybe a vector? and use the indices to place in the HashMap

1 Answers

Read lines into maybe a vector? and use the indices to place in the HashMap

That's unnecessary, if the file is just a bunch of lines and each line is a value with no marker (so index is the only indicator) you can just zip the field names and the lines together, then collect the result into a hashmap.

use std::collections::HashMap;
use std::io::{BufRead, BufReader};

fn main(){
    // fake file reading
    let bu_reader = BufReader::new("foo@example.org
hunter2
".as_bytes());

    let my_map = ["email", "pw"].into_iter()
        .zip(bu_reader.lines().map(Result::unwrap))
        .collect::<HashMap<_, _>>();
    println!("{:#?}", my_map);
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=95608a79c7d351b02b853d58158015ab

Though for flexibility and clarity I would suggest a better defined and more standard format (e.g. toml, json, yaml), and proper deserialization via serde.

Related