gpt4 book ai didi

macros - 如何在包含长度由宏指定的数组的类型上使用#[derive]?

转载 作者:行者123 更新时间:2023-11-29 07:51:02 25 4
gpt4 key购买 nike

我有这个代码:

macro_rules! count {
() => { 1 };
}

#[derive(Debug)]
struct MyStruct<T> {
field_list: [T; count!()],
}

编译器报错:

error: `derive` cannot be used on items with type macros
--> src/main.rs:7:21
|
7 | field_list: [T; count!()],
| ^^^^^^^^

有什么方法可以在包含长度由宏指定的数组的类型上使用 #[derive] 吗?

最佳答案

引用我在Github问题上的回答:

It is intentional (here is the historical record), but there is a possibility the situation could be improved in the future, and at least the error message should be rewritten to explain why it refuses to compile.

The underlying issue is that #[derive] macros need to "forward" their trait requirements to all the fields of the struct. For MyStruct to be Debug, the type of field must also be Debug. Consider this one:

#[derive(Debug)] struct MyStruct<T: FromStr> {
field: T
}

We need to generate impl<T: FromStr> Debug for MyStruct<T> where T:
Debug { ... }
(you'll see why I picked FromStr in a second). However in this case:

#[derive(Debug)] struct MyStruct<T> {
field: T::Err
}

Here the field is an associated type, so the generated code actually needs to be impl<T: FromStr> Debug for MyStruct<T> where T::Err:
Debug { ... }
.

The derive macros actually scan the field types to see whether they need to bound T or an associated type. But if you use a type macro, this breaks. The code generation can't see through the macro, so it doesn't know what bounds to generate.

When this was discovered we couldn't decide whether to let the type macro be expanded eagerly (seems like you could get into a loop or ordering issues), just copy the macro into the where clause (derives normally don't do this because it could expand to a private type, causing type errors in generated code), or something else, so we punted and made it an error.

在遵守推导的“策略”时并不能真正解决问题:(1) 它为您生成边界,(2) 它只生成可编译的代码。但是由于自定义派生是稳定的,所以您可以使用一些 crate ,例如 derivative ,通过让您重写绑定(bind)来回避问题:

#[derive(Derivative)]
#[derivative(Debug)]
struct MyStruct<T> {
#[derivative(Debug(bound="T: ::std::fmt::Debug"))]
field_list: [T; count!()],
}

关于macros - 如何在包含长度由宏指定的数组的类型上使用#[derive]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50296196/

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