An error message I can not comprehend

I'm trying to solve the activity in https://doc.rust-lang.org/rust-by-example/hello/print/fmt.html.

So assuming this tutorial is easy I just recoded the display trait with the hints on format! given at the top of the page, well doesn't work.

So far what I coded is:

struct Color{
	red: u8,
	green: u8,
	blue: u8,
}

impl Display for Color{
	fn fmt(&self, f: &mut Formatter) -> fmt::Result{
		let col = format!("({}, {}, {})", self.red, self.green, self.blue);
		let hexcol = format!("0x{:X}{:X}{:X}", self.red, self.green, self.blue);
		write!("RGB {} {}", col, hexcol)
	}
}

However the error message is confusing for a beginner:

error[E0599]: no method named write_fmt found for reference &'static str in the current scope

The first argument to write!() is the writer you are writing to, not the format string. (Otherwise, how would it know what are you writing to?)

By the way, why are you allocating separate strings for the formatting? That's unnecessary. Just write the whole
format string in one go, directly to the formatter.

Thanks, just that when writing it in one go I get following confusing message:

help: you might be missing a string literal to format with

How did you write that ?

Also, when you print bytes in hexadecimal, you should always pad them to be 2 characters long, or you may end with missing zeroes when you concatenate multiple bytes like you do here.

The format string should be "0x{:02X}{:02X}{:02X}"

1 Like

Then you are doing something else wrong, too. There's no reason writing everything in one go shouldn't work. This compiles.

1 Like

I found it after comparing what I typed with what you provide. Yes it is something else, it is a bit trivial and slightly easy to overlook at first. Anyway thanks for solving this problem.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.