如何实现自定义'fmt :: Debug'特性?

Dou*_*oug 42 rust

我猜你做的事情是这样的:

extern crate uuid;

use uuid::Uuid;
use std::fmt::Formatter;
use std::fmt::Debug;

#[derive(Debug)]
struct BlahLF {
    id: Uuid,
}

impl BlahLF {
    fn new() -> BlahLF {
        return BlahLF { id: Uuid::new_v4() };
    }
}

impl Debug for BlahLF {
    fn fmt(&self, &mut f: Formatter) -> Result {
        write!(f.buf, "Hi: {}", self.id);
    }
}
Run Code Online (Sandbox Code Playgroud)

...但是尝试实现此特征会产生:

error[E0243]: wrong number of type arguments
  --> src/main.rs:19:41
   |
19 |     fn fmt(&self, &mut f: Formatter) -> Result {
   |                                         ^^^^^^ expected 2 type arguments, found 0
Run Code Online (Sandbox Code Playgroud)

但是,这似乎是其他实现的方式.我究竟做错了什么?

cnd*_*cnd 47

根据std::fmt文档中的示例:

extern crate uuid;

use uuid::Uuid;
use std::fmt;

struct BlahLF {
    id: Uuid,
}

impl fmt::Debug for BlahLF {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Hi: {}", self.id)
    }
}
Run Code Online (Sandbox Code Playgroud)

要强调的部分是fmt::fmt::Result.没有它,你指的是普通Result类型.普通Result类型确实有两个泛型类型参数,fmt::Result没有.

  • 我想我就是那个把它添加到那里的人! (3认同)
  • 我仍然很惊讶这个例子不在这个页面上,我一直不得不用谷歌搜索这个答案。https://doc.rust-lang.org/stable/core/fmt/trait.Debug.html (2认同)
  • 不要使用“write!”进行手动调试实现。如果您手动实现“调试”,请阅读*[本页](https://doc.rust-lang.org/std/fmt/trait.Debug.html#examples)*,并使用“debug_struct”。 (2认同)