【问题标题】:How is Fmt::Display 'Cleaner' than Fmt::Debug?Fmt::Display 'Cleaner' 比 Fmt::Debug 怎么样?
【发布时间】:2020-07-28 12:49:02
【问题描述】:

所以我目前正在开始使用 Rust,并且正在通过示例阅读 Rust。
做练习,边玩边玩代码。

但在 RBE Display 函数描述中,它将 Fmt::Display 描述为比 Fmt::Debug 更“干净”。
这怎么样?在我看来,你必须做更多的工作,并编写更多的代码来尝试使 Fmt::Display 工作,而 Fmt::Debug 立即工作?

我是否误解了“更清洁”代码是什么,或者这是一个错字?

【问题讨论】:

    标签: rust coding-style


    【解决方案1】:

    Display 的 输出 通常比 Debug 更干净,而不是实现它的代码。 Debug 的输出旨在用于调试目的,提供不那么模棱两可的输出。 Display 的输出是面向用户的输出,所以它高度依赖于你的结构的含义,这就是它无法推导的原因。

    例如,考虑以下代码:

    fn main() {
        // Note that \t is the TAB character
        let output = "N\tO\tI\tC\tE";
        println!("Debug: {:?}", output);
        println!("Display: {}", output);
    }
    

    它会输出:

    Debug: "N\tO\tI\tC\tE"
    Display: N  O   I   C   E
    

    在这种情况下,Debug 将显示 str(文本)包含的字符(因为它在调试时更有用),而 Display 只会打印它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      相关资源
      最近更新 更多