如何实现自定义的“fmt::Debug"特征? [英] How to implement a custom 'fmt::Debug' trait?

查看:43
本文介绍了如何实现自定义的“fmt::Debug"特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我猜你会这样做:

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

...但是尝试实现这个特性会产生:

...but attempting to implement this trait generates:

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

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

However, that seems to be how other implementations do it. What am I doing wrong?

推荐答案

根据 std::fmt 文档:

According to the example from the 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 没有.

The part to emphasize is the fmt:: in fmt::Result. Without that you're referring to the plain Result type. The plain Result type does have two generic type parameters, fmt::Result has none.

这篇关于如何实现自定义的“fmt::Debug"特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆