This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/norude1 on 2023-11-04 14:19:21.


I was browsing this question and came across this code:

use std::fmt;

struct Foo(Vec);

impl fmt::Display for Foo {
 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 writeln!(f, "Values:")?;
 for v in &self.0 {
 write!(f, "\t{}", v)?;
 }
 Ok(())
 }
}

fn main() {
 let f = Foo(vec![42]);
 println!("{}", f);
}

`I don't particularly like the for loop, so I replaced it with for_each and got this`rust
impl fmt::Display for Foo {
 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 writeln!(f, "Values:")?;
 self.0.iter().for\_each(|v| {
 write!(f, "\t{}", v)?;
 });
 Ok(())
 }
}

But this won’t work, because the question mark operator is trying to return from the closure, not the function. How to change that?