How to print out a struct's field use macro

struct User {
    name: String,
    age: u8,
}

macro_rules! show_attriubte {
    ($st:ident, $name:ident) => {
        println!("{}", $st.$name)
    };
}

fn main() {
    let user = User {
        name: "five".to_string(),
        age: 100,
    };
    show_attriubte!(user, "name");
    //println!("{}", user.name);
}

I try to print out the attribute using the marco just for leaning .
some other related question, how to understand macro complete.
I have no idea what macro can do and can not do.

struct User {
    name: String,
    age: u8,
}

macro_rules! show_attriubte {
    ($st:ident, $name:ident) => {
        println!("{}", $st.$name)
    };
}

fn main() {
    let user = User {
        name: "five".to_string(),
        age: 100,
    };
-    show_attriubte!(example, "name");
+    show_attribute!(user, name);
    //println!("{}", user.name);
}

"name" is a literal, not an identifier. If you want to learn more about macros in Rust I highly recommend reading the Little Book of Rust Macros.

2 Likes