Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 807
Doug Avatar asked Mar 07 '14 06:03

Doug


People also ask

How do I enable debugging in Rust?

By default, rustc is built without most debug information. To enable debug info, set debug = true in your config.

What is #[ derive debug )] in Rust?

#[...] is an attribute on struct Person . derive(Debug) asks the compiler to auto-generate a suitable implementation of the Debug trait, which provides the result of {:?} in something like format!(

What is rust GDB?

rust-gdb is a prebuilt binary that comes with the Rust installation (using Rustup, for example) and is installed automatically. Basically, rust-gdb is a wrapper that loads external Python pretty-printing scripts into GDB.

What is derive in Rust?

The derive attribute allows new items to be automatically generated for data structures. It uses the MetaListPaths syntax to specify a list of traits to implement or paths to derive macros to process.


1 Answers

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.

like image 119
cnd Avatar answered Oct 06 '22 12:10

cnd