Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Last active October 25, 2025 12:49
Show Gist options
  • Save RandyMcMillan/6c87bf9a550525f4e5f3c532735df240 to your computer and use it in GitHub Desktop.
Save RandyMcMillan/6c87bf9a550525f4e5f3c532735df240 to your computer and use it in GitHub Desktop.
create_getter.rs
// 1. Declarative Macro Definition
// This macro takes a field identifier ($field:ident) and generates a public
// getter method with the same name.
macro_rules! create_getter {
($field:ident) => {
// The generated code:
pub fn $field(&self) -> &str {
// Assumes the field is a String, and returns a string slice (&str)
&self.$field
}
};
}
// 2. Struct Definition
struct User {
// The field is private by default (no 'pub'), but the generated getter is public.
name: String,
email: String,
}
// 3. Macro Invocation
impl User {
// The macro call `create_getter!(name)` expands to:
// pub fn name(&self) -> &str { &self.name }
create_getter!(name);
// We can also define a standard, non-macro-generated getter for 'email'
// just to show the difference, or call the macro again:
create_getter!(email);
// A simple constructor for the struct
pub fn new(name: &str, email: &str) -> Self {
User {
name: name.to_string(),
email: email.to_string(),
}
}
}
// 4. Usage in main function
fn main() {
let user = User::new("Alastor Moody", "[email protected]");
// We use the getter methods generated by the macro
let user_name: &str = user.name();
let user_email: &str = user.email();
println!("User Information:");
println!("Name (via getter): {}", user_name);
println!("Email (via getter): {}", user_email);
// You cannot access the fields directly because they are private:
// let private_name = user.name; // This would cause a compile error!
}
@RandyMcMillan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment