Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

rust - How to implement a custom 'fmt::Debug' trait?

I presume you do something like this:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...