- proc-macro
- TokenStream
Procedural macros
- procedural macros
- Apparently the Macro needs to be in its own Crate separate from where it is being used.
- Add proc-macro to the Cargo.toml
- Here we show that the macro is executed during the compilation.
- It needs to return a TokenStream.
examples/macros/hello-world-macro/Cargo.toml
[package] name = "hello-world-macro" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] proc-macro = true [dependencies]
examples/macros/hello-world-macro/src/lib.rs
extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro] pub fn hello_world(_item: TokenStream) -> TokenStream { println!("Hello World during compilation"); //"println!(\"Hello World that was added to the code\");".parse().unwrap() r#"println!("Hello World that was added to the code");"# .parse() .unwrap() }
examples/macros/hello-world-use/Cargo.toml
[package] name = "hello-world-use" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] hello-world-macro = { version = "0.1.0", path = "../hello-world-macro" }
examples/macros/hello-world-use/src/main.rs
extern crate hello_world_macro; use hello_world_macro::hello_world; fn main() { hello_world!(); }