#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

#2841 in Rust patterns

Download history 107/week @ 2024-03-16 135/week @ 2024-03-23 130/week @ 2024-03-30 64/week @ 2024-04-06 99/week @ 2024-04-13 82/week @ 2024-04-20 123/week @ 2024-04-27 88/week @ 2024-05-04 93/week @ 2024-05-11 83/week @ 2024-05-18 82/week @ 2024-05-25 90/week @ 2024-06-01 54/week @ 2024-06-08 75/week @ 2024-06-15 180/week @ 2024-06-22 25/week @ 2024-06-29

351 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