#oop #utility #macro #named-fields

macro roop

Provides attributes to simulate inheritance in Rust

1 unstable release

0.1.0 Sep 29, 2024

#430 in Procedural macros

Download history 193/week @ 2024-09-29 9/week @ 2024-10-06 1/week @ 2024-10-13

203 downloads per month

MIT license

9KB
109 lines

Roop

This library provides 2 attributes: class and extends.
Combination of these attributes can 'simulate' inheritance in Rust.
Note that this library and it's functions are highly experimental.

As class can be marked only struct with named fields.
The child class don't have to be marked as class.
You can't implement Deref and DerefMut traits on child class, because extends actively uses them.

Extending class outside of local module is currently not working.

use roop::*;

#[class] // Marks struct as class
struct Parent {
    a: i32,
    b: i32,
}

impl Parent {
    pub fn print_all(&self) {
        println!("a: {}, b: {}", self.a, self.b);
    }

    pub fn sum_a_b(&self) -> i32 {
        self.a + self.b
    }
}

#[extends(Parent)] // Extends Parent class, inherit all fields from Parent
struct Child {
    c: i32,
}

impl Child {
    pub fn print_all(&self) { // This will override the print_all from Parent class
        println!("a: {}, b: {}, c: {}", self.a, self.b, self.c);
    }
}

fn main() {
    let parent = Parent {
        a: 1,
        b: 2,
    };

    let child = Child {
        a: 1,
        b: 2,
        c: 3,
    };

    parent.print_all(); // Output: "a: 1, b: 2" 
    child.print_all(); // Output: "a: 1, b: 2, c: 3"

    let p_sum = parent.sum_a_b();
    let c_sum = child.sum_a_b();

    assert_eq!(p_sum, c_sum); // Will pass!
}

Dependencies

~255–710KB
~17K SLoC