// a simple macro two say hello world
macro_rules! hello {
    ($name: expr) => {
        println!("Hello, {}", $name)
    };
}

// now get two numbers added
macro_rules! add {
    ($a: expr, $b: expr) => {
        $a + $b
    };
}

// create a function

macro_rules! create_fn {
    ($name: ident) => {
        fn $name() {
            println!("Called {:?}()", stringify!($name));
        }
    };
}

// just take something from there examples
// https://doc.rust-lang.org/rust-by-example/macros/overload.html
macro_rules! test {
    ($left:expr; and $right:expr) => {
        println!(
            "{:?} and {:?} is {:?}",
            stringify!($left),
            stringify!($right),
            $left && $right
        );
    };
}

// repeatative expressions
macro_rules! find_min {
    // so cool that it pattern matches automatically
    ($x: expr) => ($x);
    // I need to understand what it's doing in here bro
    ($x: expr, $($y: expr),+) => {
        std::cmp::min($x, find_min!($($y),+))
    };
}

// here is the most useful one
// something that can generate code for anything, in my case struct
macro_rules! generate_get_fun {
    ($strct_name:ident { $($field_name:ident : $field_type: ty),+ }) => {
       $(
            fn $field_name(&self) -> $field_type {
                self.$field_name.clone()
            }
        )*
    };
}

// I just want to generate simple thing
macro_rules! single {
    ($strct_name:ident { $field_name:ident : $field_type: ty }) => {
        // here we go with paste
        paste::item! {
            pub fn [< get_ $field_name >] (&self) -> $field_type {
                self.$field_name.clone()
        }
        }
    };
}

pub struct Person {
    name: String,
    age: i32,
}

impl Person {
    generate_get_fun!(Person {
        name: String,
        age: i32
    });
}

pub struct Object {
    size: i32,
}

impl Object {
    single!(Object { size: i32 });
}

create_fn!(foo);

fn main() {
    // let's have some simple ones
    hello!("Himanshu");
    println!("{} + {} = {}", 10, 20, add!(10, 20));
    // I really liked how it worked in here,
    // just so amazing I can't wait more to see what else can I do with a macro
    foo();

    // let's implement something more complex
    // I liked this one too, good going
    test!(true; and false);

    // find minimum number
    // and it works
    println!("{}", find_min!(3, 1, 5, 3, 2));

    // will check a few later
    // https://doc.rust-lang.org/rust-by-example/macros/dry.html
    let person = Person {
        name: "Himansh".to_string(),
        age: 20,
    };

    let name = person.name();
    let age = person.age();

    let object = Object { size: 3 };

    let size = object.get_size();
}macro_rules! say_hello_to {
    ($name:expr) => {
        concat!("Hello, ", $name, "!")
    };
}

fn main() {
    println!("{}", say_hello_to!("Alice"));
}
// example of vec![1, 2, 3] macro
macro_rules! vec {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}

Rust相关代码片段

rust : nearest neighbour algorithm

Rust Change Character into Integer

Rust variables

Data Types Rust

rust enum values

rust protobuf

rust byte literal

rust unzip

global variables rust

rust error

rust don't open window on run

rust unused Result that must be used

rust run async function

rust how to add standard crate to cargo toml

rust save image file

rust print char variables

rust charxor

rust match ok err

rust vector get element at index

serde derive feature

pow in rust

type annotation needed rust

sum of squares formula

rust int types

rust unwrap error

rust permutations

rust match guard enum variant

rust generic numeric type

rust move out of mut ref

rust unpack struct with custom name

rust change enum type of self

rust switch from nightly to stable

chromiumoxide rust proxy

rust expected usize found i32

println! before user input not printing

rust give const value to enum member

rust chromiumoxide proxy server

rust database

difference between the dedup and unique

Local connect to a rust server

rust listdir to string list

rs implement hash for enum with special case

rust fibonacci sequence

how to install some version of rust as default

verify and extract login from an email address

Parse the mime type of a http response

Rust Listen on unused port TCP/IP

create bin rust

rust itertools

why rust analyzer only work with cargo

Print Hashmap in rust

rust iterate over vector with index

length of array in rust

check length in rust

valence system ecs rust

rust vs node performance

rust enum with value

what is ? in rust

match and store variable in rust

rust env_logger default level

rust create array with x entries

rust random bytes < 32

rust random bytes > 32

Rust Download windows

rust vector with capacity

read from console rust

rust vector join

rust implement partialeq

rust cmp ordering match

rust dev dependencies

rust parse i32

std::cmp::Ordering

do while rust

rust to ascii code

rust chars lowercase

divide a string rust index

bevy optional resource

add function to struct rust

rust sort iterator

rust create slice from vector