Macros

  • Macros explanation

  • Invoke macro

    • something!()

  • Macro substitution

    • $something

  • Macro capture

    • $something:kind

Declarative macros

Procedural macros

Derive Macros

  • #[derive]  is a convenient way to apply macros that automatically implement traits for an entire struct (or enum). When you use #[derive(...)] , the compiler automatically generates the implementation for you. Without derive, you’d need to write it manually.

derive(debug)
  • Automatic implementation of the Debug  trait, using #[derive(Debug)] :

    #[derive(Debug)] // Compiler implements Debug
    struct Point {
        x: i32,
        y: i32,
    }
    
    fn main() {
        let p = Point { x: 3, y: 4 };
        println!("{:?}", p); // Output: Point { x: 3, y: 4 }
    }
    
  • Manual implementation of the Debug  trait, without #[derive(Debug)] :

    use std::fmt;
    
    struct Point {
        x: i32,
        y: i32,
    }
    
    // Manual implementation of the Debug trait
    impl fmt::Debug for Point {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
        }
    }
    
    fn main() {
        let p = Point { x: 3, y: 4 };
        println!("{:?}", p); // Output: Point { x: 3, y: 4 }
    }