Skip to content

Instantly share code, notes, and snippets.

@U007D
Created September 4, 2020 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save U007D/3d64a294cf15cb42a6a4263131123451 to your computer and use it in GitHub Desktop.
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
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