Compile random number in the code using macro



examples/macros/random-constant-macro/Cargo.toml
[package]
name = "random-constant-macro"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.8.5"


[lib]
proc-macro = true

examples/macros/random-constant-macro/src/lib.rs
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro]
pub fn get_random(item: TokenStream) -> TokenStream {
    match item.to_string().as_str() {
        "u16" => {
            let x = rand::random::<u16>();
            format!("{:?}", x).parse().unwrap()
        }
        "i32" => {
            let x = rand::random::<i32>();
            format!("{:?}", x).parse().unwrap()
        }
        _ => panic!("Unsupported type '{}'", item),
    }
}

examples/macros/random-constant/Cargo.toml
[package]
name = "random-constant"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.8.5"
random-constant-macro = { version = "0.1.0", path = "../random-constant-macro" }

examples/macros/random-constant/src/main.rs
//macro_rules! set_random_number {
//    () => {
//        println!("Hello World!");
//    };
//}

// const RANDOM_CONSTANT: u16 = 42;
// This is not very random, is it?
//
// const RANDOM_CONSTANT: u16 = rand::random();
// cannot call non-const fn `random::<u16>` in constants

extern crate random_constant_macro;
use random_constant_macro::get_random;

//const RANDOM_CONSTANT: u16 = get_random!(u16);
const RANDOM_CONSTANT: i32 = get_random!(i32);

fn main() {
    let random_number: u16 = rand::random();
    println!("random_number: {random_number}");

    println!("random_constant: {RANDOM_CONSTANT}");
}

TODO: #[macro_export]