#named #enums #constant #const #proc-macro #debugging

named_constants

过程宏使枚举在 C/C++ 或 C# 等语言中表现得像命名常量。

2 个不稳定版本

0.2.0 2022 年 11 月 12 日
0.1.0 2020 年 10 月 13 日

#2132 in Rust 模式

Download history 54/week @ 2024-04-03 10/week @ 2024-04-10 4/week @ 2024-04-17 11/week @ 2024-04-24 10/week @ 2024-05-01 95/week @ 2024-05-08 22/week @ 2024-05-15 17/week @ 2024-05-22 9/week @ 2024-05-29 36/week @ 2024-06-05 85/week @ 2024-06-12 51/week @ 2024-06-19 30/week @ 2024-06-26 16/week @ 2024-07-03 10/week @ 2024-07-10

63 个月下载量

MIT 许可证

22KB
423 代码行

命名常量

过程宏使枚举在 C/C++ 或 C# 等语言中表现得像命名常量。

将此属性应用于枚举,它将被重写为新类型结构。枚举变体将被转换为关联常量。

示例

use named_constants::named_constants;

#[named_constants]
// Derives are applied to the newtype wrapper
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
// Required repr to specify the underlying type
#[repr(i32)]
pub enum CardSuit {
	CLUBS,      // (= 0) Starts from zero
	DIAMONDS,   // (= 1) Autoincrements the previous value
	HEARTS = 4, // (= 4) Direct assignment
	SPADES,     // (= 5) Autoincrements the previous value
}

let clubs = CardSuit::CLUBS;
let weird = CardSuit(14); // Legal!

实现说明

在上面的示例中,CardSuit 被转换为

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(transparent)]
pub struct CardSuit(pub i32);
impl CardSuit {
	pub const CLUBS: CardSuit = CardSuit(0);
	pub const DIAMONDS: CardSuit = CardSuit(1);
	pub const HEARTS: CardSuit = CardSuit(4);
	pub const SPADES: CardSuit = CardSuit(4 + 1);
}

许可证

根据 MIT 许可证 授权,请参阅 license.txt

贡献

除非你明确声明,否则任何有意提交以包含在你提供的作品中的贡献,均应按上述方式授权,不附加任何额外条款或条件。

无运行时依赖