Created
October 22, 2025 09:42
-
-
Save sug0/d471c9f0a65fa3f7515c00a826c7e778 to your computer and use it in GitHub Desktop.
Go iota in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| macro_rules! __iotadef_recur { | |
| ($total:expr, $expr:expr, $t:ty, $head:ident) => { | |
| pub const $head: $t = const { const IOTA: $t = $total - 1; $expr }; | |
| }; | |
| ($total:expr, $expr:expr, $t:ty, $head:ident, $( $tail:ident ),*) => { | |
| pub const $head: $t = const { | |
| #[repr($t)] | |
| enum RecurCount { | |
| $( $tail, )* | |
| ____NumberElementsLeft, | |
| } | |
| const IOTA: $t = $total - RecurCount::____NumberElementsLeft as $t - 1; | |
| $expr | |
| }; | |
| __iotadef_recur!( | |
| $total, | |
| $expr, | |
| $t, | |
| $( $tail ),* | |
| ); | |
| }; | |
| } | |
| macro_rules! iotadef { | |
| ($vis:vis $name:ident { $firstdef:ident : $t:ty = $expr:expr $(, $def:ident )* $(,)? }) => { | |
| #[allow(dead_code)] | |
| $vis mod $name { | |
| #[repr($t)] | |
| enum Count { | |
| $firstdef, | |
| $( $def, )* | |
| ____TotalNumberElements, | |
| } | |
| __iotadef_recur!( | |
| Count::____TotalNumberElements as $t, | |
| $expr, | |
| $t, | |
| $firstdef, | |
| $( $def ),* | |
| ); | |
| } | |
| } | |
| } | |
| iotadef!(pub cenas { | |
| A: isize = IOTA << 1, | |
| B, | |
| C, | |
| D, | |
| }); | |
| fn main() { | |
| println!("{}", cenas::A); | |
| println!("{}", cenas::B); | |
| println!("{}", cenas::C); | |
| println!("{}", cenas::D); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment