here are a few suggestions:
Use unwrap()
instead of match to unwrap the Result
values returned by lines()
. This can make your code more concise and easier to read. For example, instead of:
match (nextline1, nextline2) {
(Some(line1), Some(line2)) => {
match (line1, line2) {
(Ok(line1), Ok(line2)) => {
// ...
}
_ => { /* handle error */ }
}
}
_ => { /* handle error */ }
}
You can write:
let line1 = nextline1.unwrap()?;
let line2 = nextline2.unwrap()?;
This assumes that you're OK with your program panicking if there is an error reading a line from either file. If you'd rather handle the errors more gracefully, you can use match
or ?
to handle the Result
values explicitly.
Use for
loops instead of loop
loops with next()
. This can make your code more concise and easier to read. For example, instead of:
let mut chars1 = line1.chars();
let mut chars2 = line2.chars();
let mut char1 = chars1.next();
let mut char2 = chars2.next();
loop {
match (char1, char2) {
(Some(c1), Some(c2)) => {
// ...
}
_ => break,
}
char1 = chars1.next();
char2 = chars2.next();
}
You can write:
for (c1, c2) in line1.chars().zip(line2.chars()) {
// ...
}
This assumes that you want to compare characters one-by-one between the two lines. If you'd rather compare whole lines at a time, you can modify this loop accordingly.
Consider using the zip_longest
method from the itertools
crate instead of manually zipping the lines. This can simplify your code and make it more concise. For example, instead of:
let mut nextline1 = buf_read1.next();
let mut nextline2 = buf_read2.next();
loop {
match (nextline1, nextline2) {
(Some(line1), Some(line2)) => {
// ...
}
_ => break,
}
nextline1 = buf_read1.next();
nextline2 = buf_read2.next();
}
You can write:
use itertools::Itertools;
for (line1, line2) in buf_read1.lines().zip_longest(buf_read2.lines()) {
// ...
}
This assumes that you've added the itertools
crate to your Cargo.toml
file.
I hope these suggestions are helpful!