rust - for <'r, ' s> fn( &'r MyType<' s>) -> bool 在 `impl std::fmt::Debug` 定义中的什么位置?

标签 rust

我有这种类型:

struct Ctx;

type CmdHandler = fn(&mut Ctx) -> bool;

#[derive(Debug)]
pub struct Cmd {
    pub name: String,
    pub handler: CmdHandler,
}

impl Cmd {
    pub fn new(name: String, handler: CmdHandler) -> Cmd {
        Cmd { name, handler }
    }
}

它最终会抛出这个错误:

error[E0277]: `for<'r> fn(&'r mut Ctx) -> bool` doesn't implement `std::fmt::Debug`
 --> src/main.rs:8:5
  |
8 |     pub handler: CmdHandler,
  |     ^^^^^^^^^^^^^^^^^^^^^^^ `for<'r> fn(&'r mut Ctx) -> bool` cannot be formatted using `:?` because it doesn't implement `std::fmt::Debug`
  |
  = help: the trait `std::fmt::Debug` is not implemented for `for<'r> fn(&'r mut Ctx) -> bool`
  = note: required because of the requirements on the impl of `std::fmt::Debug` for `&for<'r> fn(&'r mut Ctx) -> bool`
  = note: required for the cast to the object type `std::fmt::Debug`

我不知道如何实现这个特性。绊倒我的部分是 for<'r, 's> fn(&'r mut lib::server::cmd::Ctx<'s>) -> bool ;我无法弄清楚这在 impl std::fmt::Debug 中的位置定义。

最佳答案

Debug 这样的特征的自动派生通过递归委托(delegate)给每个字段的 Debug 实现来工作。在这种情况下,字段 CmdHandler 是函数指针的别名,它不实现 Debug,因此您不能自动派生 Debug Cmd 因为它的 handler 字段没有实现 Debug

解决这个问题的方法是 manually implement Debug .一种可能的实现方式是:

impl fmt::Debug for Cmd {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Cmd {{ name: {:?} }}", self.name)
    }
}

这将打印为:Cmd { name: "Something"}

正如@logansfmyth 所指出的,您还可以使用 f.debug_struct构建 DebugStruct 的方法:

impl fmt::Debug for Cmd {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Cmd")
            .field("name", &self.name)
            .finish()
    }
}

在这种情况下,这将打印与上面相同的内容,除非您将其格式化为 {:#?} 而不是 {:?}.

关于rust - for <'r, ' s> fn( &'r MyType<' s>) -> bool 在 `impl std::fmt::Debug` 定义中的什么位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50545897/

相关文章:

rust - 如何使用单个 Sublime Text 快捷方式构建和运行 Rust 代码?

rust - 如果它们等于最接近于零,有没有办法告诉 rust 选择正数(例如 : -2 0 2) => 2

rust - 我如何接受同一个 Serde 字段的多个反序列化名称?

rust - 哪里有课!红 bean 杉的宏

input - 如何在 Rust 1.0 中读取用户输入的整数?

unit-testing - 在 Rust 的测试中创建、读取和删除文件时的奇怪行为

rust - 如何找到当前 Rust 编译器的默认 LLVM 目标三元组?

generics - 如何定义一个返回自己类型的 Rust 函数类型?

rust - 不能借用为不可变的,因为它在函数参数中也被借用为可变的

rust - 是否使用rust 格式!宏提供用户指定的填充字符