如何修复“在此范围内找不到派生宏"? [英] How do I fix "cannot find derive macro in this scope"?
问题描述
我有这个:
#[derive(FromPrimitive)]
pub enum MyEnum {
Var1 = 1,
Var2
}
还有一个错误:
error: cannot find derive macro `FromPrimitive` in this scope
|
38 | #[derive(FromPrimitive)]
| ^^^^^^^^^^^^^
为什么我会得到这个?我该如何解决?
Why do I get this? How do I fix it?
推荐答案
编译器有一个一小组内置的派生宏.对于任何其他人,您必须先导入自定义 derive
才能使用它们.
The compiler has a small set of built-in derive macros. For any others, you have to import the custom derive
s before they can be used.
在 Rust 1.30 之前,您需要在提供宏的 crate 的 extern crate
行上使用 #[macro_use]
.使用 Rust 1.30 及更高版本,您可以使用
它们.
Before Rust 1.30, you need to use #[macro_use]
on the extern crate
line of the crate providing the macros. With Rust 1.30 and up, you can use
them instead.
在这种情况下,您需要从 num_derive
crate 中导入 FromPrimitive
:
In this case, you need to import FromPrimitive
from the num_derive
crate:
Rust 1.30 之后
use num_derive::FromPrimitive; // 0.2.4 (the derive)
use num_traits::FromPrimitive; // 0.2.6 (the trait)
Rust 1.30 之前
#[macro_use]
extern crate num_derive; // 0.2.4
extern crate num_traits; // 0.2.6
use num_traits::FromPrimitive;
使用
#[derive(Debug, FromPrimitive)]
pub enum MyEnum {
Var1 = 1,
Var2,
}
fn main() {
println!("{:?}", MyEnum::from_u8(2));
}
每个项目都有自己的包,包含自己的派生宏.一个小样本:
Each project has their own crate containing their own derive macros. A small sample:
- Num (例如
FromPrimitive
) =>num_derive
- Serde(例如
Serialize
、Deserialize
)=>serde_derive
- Diesel (e.g.
Insertable
,Queryable
) =>diesel
(它实际上和普通的箱子一样!)
- Num (e.g.
FromPrimitive
) =>num_derive
- Serde (e.g.
Serialize
,Deserialize
) =>serde_derive
- Diesel (e.g.
Insertable
,Queryable
) =>diesel
(it's actually the same as the regular crate!)
一些板条箱重新导出其派生宏.例如,您可以使用 Serde 的 derive
功能 然后直接从 serde
crate 中导入:
Some crates re-export their derive macros. For example, you can use the derive
feature of Serde and then import it from the serde
crate directly:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
use serde::{Serialize, Deserialize}; // imports both the trait and the derive macro
<小时>
FromPrimitive
实际上是 Rust 1.0 之前标准库的一部分.它不足以继续存在于标准库中,因此将其移至外部 num crate.一些非常旧的参考资料可能尚未针对此更改进行更新.
FromPrimitive
was actually part of the standard library before Rust 1.0. It wasn't useful enough to continue existing in the standard library, so it was moved to the external num crate. Some very old references might not have been updated for this change.
有关将类 C 枚举转换为整数的更多信息,请参阅:
For more information about converting C-like enums to and from integers, see:
这篇关于如何修复“在此范围内找不到派生宏"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!