Created
September 4, 2020 10:43
-
-
Save U007D/3d64a294cf15cb42a6a4263131123451 to your computer and use it in GitHub Desktop.
imperative vs declarative loop - a case where the traditional for loop is easier to read AND write
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn iterative_save<W: Write>(&self, mut wtr: W) -> Result<&Self> { | |
for row in self { | |
for (i, col) in row.iter().enumerate() { | |
match i { | |
0 => wtr.write_all(col.as_bytes())?, | |
_ => { | |
wtr.write_all(b",")?; | |
wtr.write_all(col.as_bytes())? | |
} | |
} | |
} | |
wtr.write_all(b"\n")?; | |
} | |
Ok(self) | |
} | |
fn declarative_save<W: Write>(&self, mut wtr: W) -> Result<&Self> { | |
self.iter().try_for_each(|row| { | |
row.iter().enumerate().try_for_each(|(i, col)| match i { | |
0 => wtr.write_all(col.as_bytes()), | |
_ => wtr | |
.write_all(b",") | |
.and_then(|_| wtr.write_all(col.as_bytes())), | |
})?; | |
wtr.write_all(b"\n") | |
})?; | |
Ok(self) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment