I have the following type:
type RangeFn = fn(&Value, &Value) -> bool;
Now I want to put it with this struct
:
#[derive(Debug)]
struct Range {
fun: RangeFn,
}
But if I have a struct
that takes RangeFn
as a parameter, then I can't seem to have it derive from Debug
. How do I make RangeFn
compatible with the Debug
trait?
You can't implement (or derive) a trait you don't own on a type you don't own.
However, that's not what you want to do. What you want is to implement Debug
for Range
, but you can't do that by deriving because fn
s don't implement Debug
.
Indeed, deriving Debug
requires all fields to be Debug
as well. Then you are stuck with implementing Debug
by yourself; It is after all, just a normal trait:
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);
}
(link to playground)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With