尝试实现核心::fmt::显示



我正在尝试为我的二叉树实现核心::fmt::Show。这是我的实现代码:

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

但是编译器抛出以下错误:

编译binary_tree v0.0.1 (file:///home/guillaume/projects/binary_tree) src/binary_tree.rs:60:2: 77:3 错误:方法 fmt 具有不兼容的 trait 类型:预期 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 };

我不明白为什么。完整的代码可以在这里找到。欢迎对我的代码提出任何评论。

错误告诉您该方法fmt没有它期望的类型,特别是它找到了一个 &-ptr(即 &str),其中应该有一个 FormatError。

方法签名更改为此将修复您的编译错误:

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

我已经在 github 上发送了一个拉取请求,该请求进行了此更改(并且还修复了您的测试,以便我可以验证它是否有效)

@McPherrinM提出的答案是解决错误,但 rustc 仍然会发出一些警告。这是用于删除警告的代码:

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
}

这一切都是为了确保将错误消息转发给此函数的调用方。

问题:

如果

发生错误,该函数将以递归方式继续,如果弹出多个错误消息,则最后一个将覆盖较旧的错误消息。难道不是吗?

最新更新