我有以下类型:
type RangeFn = fn(&Value, &Value) -> bool;
现在我想用这个struct
:
#[derive(Debug)]
struct Range {
fun: RangeFn,
}
但是如果我有一个以struct
为参数的RangeFn
,那么我似乎无法从Debug
得到它。如何使RangeFn
与Debug
特性兼容?
You can't implement (or derive) a trait you don't own on a type you don't own.
但是,这不是你想要做的。你想要的是为Debug
实现Range
,但你不能通过派生来做到这一点,因为fn
s没有实现Debug
。实际上,导出Debug
也需要所有字段都是Debug
。然后你就会坚持自己实施Debug
;毕竟,这只是一个正常的特征:
type RangeFn = fn(&(), &()) -> bool;
struct Range {
fun: RangeFn,
other_field: u32,
}
impl std::fmt::Debug for Range {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> {
f.debug_struct("Range")
.field("other_field", &self.other_field)
.finish()
}
}
fn main() {
let r = Range {
fun: |_, _| true,
other_field: 42,
};
println!("{:?}", r);
}
(Qazxswpoi)