我有这种类型:
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/