Dup Ver Goto 📝

HashSet_001

PT2/lang/rust/examples does not exist
To
88 lines, 232 words, 2086 chars Page 'HashSet_001' does not exist.

This is my first attempt at rewriting in Rust the following two-line Python program:

#!/usr/bin/env python
s = lambda fn: set(open(fn).read().rstrip().splitlines())
print("\n".join(s("a.txt").intersection(s("b.txt"))))

Rough Version

use std::fs::read_to_string;
use std::collections::HashSet;

fn read_lines(filename: &str) -> HashSet<String> {
    let hashset : HashSet<String> = read_to_string(filename)
        .unwrap()
        .lines()
        .map(String::from)
        .collect();
    hashset
}

fn main() {
    let fn1 = "a.txt";
    let fn2 = "b.txt";
    let set1 = read_lines(fn1);
    let set2 = read_lines(fn2);
    for x in set1.intersection(&set2) {
        println!("{}",x);
    }
}

Eliminating unwrap

use std::fs::read_to_string;
use std::collections::HashSet;

fn read_lines(filename: &str) -> std::io::Result<HashSet<String>> {
    let hashset : HashSet<String> = read_to_string(filename)?
        .lines()
        .map(String::from)
        .collect();
    Ok(hashset)
}

fn main() {
    let fn1 = "a.txt";
    let fn2 = "b.txt";
    let r1 = read_lines(fn1);
    let r2 = read_lines(fn2);
    if let (Ok(set1),Ok(set2)) = (r1,r2) {
        for x in set1.intersection(&set2) {
            println!("{}",x);
        }
    } else {
        println!("Error has occurred");
    }
}

Printing Errors

use std::fs::read_to_string;
use std::collections::HashSet;

fn read_lines(filename: &str) -> std::io::Result<HashSet<String>> {
    let hashset : HashSet<String> = read_to_string(filename)?
        .lines()
        .map(String::from)
        .collect();
    Ok(hashset)
}

fn main() {
    let fn1 = "a.txt";
    let fn2 = "b.txt";
    let r1 = read_lines(fn1);
    let r2 = read_lines(fn2);
    if let (Ok(set1),Ok(set2)) = (&r1,&r2) {
        for x in set1.intersection(&set2) {
            println!("{}",x);
        }
    } else if let Err(err) = &r1 {
        println!("Error has occurred with file1: {}",err);
    } else if let Err(err) = &r2 {
        println!("Error has occurred with file2: {}",err);
    }
}