Rust 在哪里为<';r、 &x27;s>;fn(&;x27;r MyType<;&;x27;s>;)->;bool进入'impl std::fmt::Debug'定义?
我有这种类型:Rust 在哪里为<';r、 &x27;s>;fn(&;x27;r MyType<;&;x27;s>;)->;bool进入'impl std::fmt::Debug'定义?,rust,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,
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 }
}
}
它最终抛出以下错误:
错误[E0277]:`for bool`未实现`std::fmt::Debug`
-->src/main.rs:8:5
|
8 |发布处理程序:CmdHandler,
|无法使用“:?”对bool”进行格式化,因为它未实现“std::fmt::Debug”`
|
=help:trait`std::fmt::Debug`没有为`for bool实现`
=注意:由于对`std::fmt::Debug`for`&的impl的要求,因此需要`
=注意:强制转换到对象类型'std::fmt::Debug'时需要`
我不知道如何实现这种特性。让我大吃一惊的是fn的
(&'r mut lib::server::cmd::Ctx自动派生类似于Debug
的特征是递归地委托给每个字段的Debug
实现。在这种情况下,字段CmdHandler
是函数指针的别名,它不实现Debug
,因此无法自动派生Debug
用于Cmd
,因为其处理程序
字段未实现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所指出的,您还可以使用该方法来构建:
在这种情况下,这将与上面的打印相同,只是如果您将其格式化为{:?}
而不是{:?}
则可以使用漂亮的打印。好主意,将扩展。
impl fmt::Debug for Cmd {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Cmd")
.field("name", &self.name)
.finish()
}
}