如何为包含函数类型别名的结构实现Debug?

问题描述 投票:0回答:1

我有以下类型:

type RangeFn = fn(&Value, &Value) -> bool;

现在我想用这个struct

#[derive(Debug)]
struct Range {
    fun: RangeFn,
}

但是如果我有一个以struct为参数的RangeFn,那么我似乎无法从Debug得到它。如何使RangeFnDebug特性兼容?

rust
1个回答
6
投票

You can't implement (or derive) a trait you don't own on a type you don't own.

但是,这不是你想要做的。你想要的是为Debug实现Range,但你不能通过派生来做到这一点,因为fns没有实现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)

© www.soinside.com 2019 - 2024. All rights reserved.