#vec #traits #object #box #macro

vec_box

A single macro to create a vec of boxed elements, for trait objects

1 stable release

Uses old Rust 2015

1.0.0 Jan 15, 2017

#2783 in Rust patterns

Download history 77/week @ 2023-12-06 74/week @ 2023-12-13 74/week @ 2023-12-20 27/week @ 2023-12-27 38/week @ 2024-01-03 93/week @ 2024-01-10 93/week @ 2024-01-17 42/week @ 2024-01-24 50/week @ 2024-01-31 59/week @ 2024-02-07 79/week @ 2024-02-14 74/week @ 2024-02-21 144/week @ 2024-02-28 90/week @ 2024-03-06 105/week @ 2024-03-13 133/week @ 2024-03-20

479 downloads per month
Used in 19 crates (2 directly)

ISC/MIT/Apache-2.0

3KB
63 lines

vec_box!

A small macro to box up elements in an array for use with trait objects.

Example

#[macro_use]
extern crate vec_box;

struct A {
    x: u32
}

impl A {
    fn new(x: u32) -> A {
        A { x: x }
    }
}

struct B {
    x: u32,
    y: u32
}

impl B {
    fn new(x: u32) -> B {
        B { x: x, y: x }
    }
}

trait C {
    fn get(&self) -> u32;
}

impl C for A {
    fn get(&self) -> u32 {
        self.x
    }
}

impl C for B {
    fn get(&self) -> u32 {
        self.x + self.y
    }
}

fn main() {
    let v: Vec<Box<C>> = vec_box![
        A::new(1),
        B::new(1),
        A::new(2)
    ];

    assert_eq!(
        v.iter().fold(0, |acc, ref x| acc + x.get()),
        5
    );
}

No runtime deps