r/rust•
norude1

How to use "?" inside closures

🙋 seeking help & advice

I was browsing [this question](https://stackoverflow.com/questions/30633177/implement-fmtdisplay-for-vect) and came across this code:

```rust

use std::fmt;
struct Foo(Vec<u8>);
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?

​

​

​

Posted Nov 4, 2023, 1:19 PM UTC

3126
Loading comments…