#traits #box #vec #object #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

#2807 in Rust patterns

Download history 77/week @ 2024-07-19 75/week @ 2024-07-26 63/week @ 2024-08-02 77/week @ 2024-08-09 56/week @ 2024-08-16 62/week @ 2024-08-23 52/week @ 2024-08-30 67/week @ 2024-09-06 68/week @ 2024-09-13 83/week @ 2024-09-20 81/week @ 2024-09-27 33/week @ 2024-10-04 35/week @ 2024-10-11 61/week @ 2024-10-18 77/week @ 2024-10-25 118/week @ 2024-11-01

291 downloads per month
Used in 18 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