Moebius
Moebius

Reputation: 6528

Trying to implement core::fmt::Show

I am trying to implement the core::fmt::Show for my binary tree. This is my implement code :

impl<T: PartialEq + PartialOrd + Show> Show for Node<T>
{
    fn fmt(&self, f: &mut Formatter) -> Result<(), &str>
    {
        match self.left {
            Some(ref x) => {x.fmt(f);},
            None => {}
        };
        match self.value {
            Some(ref x) => {
                write!(f, "{}", x.to_string().as_slice());
            },
            None => {}
        };
        match self.right {
            Some(ref x) => {x.fmt(f);},
            None => {}
        };
        Ok(())
    }
}

But the compiler throw the following error :

Compiling binary_tree v0.0.1 (file:///home/guillaume/projects/binary_tree) src/binary_tree.rs:60:2: 77:3 error: method fmt has an incompatible type for trait: expected enum core::fmt::FormatError, found &-ptr [E0053] src/binary_tree.rs:60 fn fmt(&self, f: &mut Formatter) -> Result<(), &str> src/binary_tree.rs:61 { src/binary_tree.rs:62 match self.left { src/binary_tree.rs:63 Some(ref x) => {x.fmt(f);}, src/binary_tree.rs:64 None => {} src/binary_tree.rs:65 };

I can't understand why. The complete code could be found here. Any comments about my code are welcome.

Upvotes: 1

Views: 648

Answers (2)

Moebius
Moebius

Reputation: 6528

The answer proposed by @McPherrinM is solving the error, but rustc still fire some warning. This it the code to use to delete the warnings :

fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::FormatError>
{
    let mut result = Ok(());
    match self.left {
        Some(ref x) => {
            result = result.and(x.fmt(f));
        },
        None => {;}
    };
    match self.value {
        Some(ref x) => {
            result = result.and(write!(f, "{}", x.to_string().as_slice()));
        },
        None => {;}
    };
    match self.right {
        Some(ref x) => {
            result = result.and(x.fmt(f));
        },
        None => {;}
    };
    result
}

It is all about making sure you forward the error message to this function's caller.

Question :

If an error occur, the function will carry on recursively and if more than one error message pop, the last one one will override the older one. Isn't that right ?

Upvotes: 0

McPherrinM
McPherrinM

Reputation: 4614

The error is telling you that the method fmt does not have the type it expects, and in particular it found a &-ptr (i.e., the &str) where there should be a FormatError.

changing the method signature to this will fix your compilation error:

  fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::FormatError>

I have sent a pull request on github that makes this change (and also fixes your test so I could verify it does work)

Upvotes: 4

Related Questions