How to implement Display for struct with String

Hello everyone
Just starting with rust. Trying to implement Display for a struct

 use std::fmt::Formatter;

struct Person {
    name: String,
    age: u32,
}

impl std::fmt::Display for Person {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        writeln!("name: {}, age: {}", self.age, self.name)
    }
}
fn main() {
    let john = Person {
        name: String::from("john"),
        age: 48,
    };

    println!("Person {}", john);
}

here is the error i'm getting

error: format argument must be a string literal
  --> src/main.rs:11:39
   |
11 |         writeln!("name: {}, age: {}", self.name, self.age)

So, how do i implement Display for struct where i have String type attribute?

thanks

You can do &self.name instead.

The first argument to writeln! should be the Formatter, f:

writeln!(f, "name: {}, age: {}", self.name, self.age)
2 Likes

thanks mbrubeck, this works

another question if you don't mind, how you figured this out?
i looked at the documentation and it did not talk about Formatter being
first argument

thanks

Those docs link to the write! docs, which talk more explicitly about the “writer” argument (type that implements fmt::Write or io::Write). Though these docs are still not very clear.

In practice I think I learned this from the example in the Display docs.

1 Like

Also, just think about it: how would writeln!() know where to write if you didn't specify it?

Even so, it may be worthwhile to file an issue against the documentation. It seems a large number of people are starting to learn Rust during this extended period of "working from home", so the issue will be encountered again and again.

4 Likes

I've been bitten by this too many times to count, even though I have experience in Rust. If you're able to say, how difficult would it be to get a better error message in the compiler? The trivial case to check is if the first argument is a string literal.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.