【问题标题】:How to implement a custom 'fmt::Debug' trait?如何实现自定义的“fmt::Debug”特征?
【发布时间】:2014-03-07 06:52:44
【问题描述】:

我想你会这样做:

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);
    }
}

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

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

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

【问题讨论】:

  • 粘贴示例 main/rust playground 链接也会很有用。

标签: rust


【解决方案1】:

根据std::fmt docs的例子:

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)
    }
}

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

【讨论】:

猜你喜欢
  • 2017-08-22
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 2015-08-07
相关资源
最近更新 更多