gpt4 book ai didi

rust - 如何为包含函数类型别名的结构实现调试?

转载 作者:行者123 更新时间:2023-11-29 08:10:47 25 4
gpt4 key购买 nike

我有以下类型:

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

现在我想把它和这个 struct 放在一起:

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

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

最佳答案

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

但是,这不是您想要做的。你想要的是为 Range 实现 Debug,但是你不能通过推导来实现,因为 fn 没有实现 调试。事实上,派生 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);
}

( link to playground )

关于rust - 如何为包含函数类型别名的结构实现调试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com