I just wanted to write two lines, this is the sketch so far:
impl Display for TestResult {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let summary = self.outcome.summary().to_string();
let elapsed = format!("{}ms", self.elapsed.as_millis());
let description = &self.description;
writeln!(f, "{summary:7} {elapsed:6} {description}")?;
writeln!(f, " Something went wrong")?;
Ok(())
}
}
I just couldn't figure out what I was supposed to be returning from fmt(), not realising that I just need the Ok(()). Adding the ?s also avoids the compiler warnings.
It just seemed that every example on the world-wide-web had exactly one call to write!() or writeln()
I see. just a reminder, if you have trouble figure out what to return, the first thing to check is the type definition.
for example, if you lookup std::fmt::Result, it is an alias for Result<(), std::fmt::Error>
well, I guess most sample code assumes you already are familiar with error handling in rust, particularly the Result type.
again, a good place to look is how the trait is implemented in the standard library. for example, scrollong through the "Implementors" section of std::fmt::Display, you can find complex types such as PanicInfo or Backtrace, then you can simply click the "source" link, which will navigate to the source code of the impl block here:
impl fmt::Display for MinMax {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Use `self.number` to refer to each positional data point.
write!(f, "({}, {})", self.0, self.1)
}
}
And rewrite it like so:
impl fmt::Display for MinMax {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Use `self.number` to refer to each positional data point.
write!(f, "({}", self.0)?;
write!(f, ", {})", self.1)?;
Ok(())
}
}
The error handling is equivalent, no?
In any case, would we expect an error to ever occur here?
Yes an error could occur because this is the error of the formatter. One could use your debug impl to write into a fixed size buffer. A write!() could now result in an error if the buffer is full