2

Consider the following piece of code:

use std::fmt::Write;

struct X;

impl std::fmt::Display for X {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        f.write_char('X')
    }
}

fn main() {
    let x = X{};
    println!("{}", x.to_string());
}

Why does implementing Display for a struct add the ability to call to_string() on it? The only method provided by Display is fmt(), so there has to be something else going on under the covers.

s3rvac
  • 9,301
  • 9
  • 46
  • 74
  • 2
    I believe your question is answered by the answers of [Should I implement Display or ToString to render a type as a string?](https://stackoverflow.com/q/27769681/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jun 18 '18 at 18:44
  • 1
    @Shepmaster Yes, you are right. I have overlooked this answer when looking for an explanation. Feel free to close my question as already answered (or I can remove it). – s3rvac Jun 18 '18 at 18:53
  • Nah, this will be a good signpost as the duplicate's title isn't very obvious that it's going to explain the *why*, even though the answer does. – Shepmaster Jun 18 '18 at 19:09

0 Answers0