-
-
Save RandyMcMillan/6c87bf9a550525f4e5f3c532735df240 to your computer and use it in GitHub Desktop.
create_getter.rs
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
| // 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! | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=765012841a0ef18877c70cb26a42b572