有无堆特征对象吗?

Is there a heapless trait object?

有没有办法在堆栈内存中完全实现特征对象?

这是我使用的代码 Box 因此堆内存:

extern crate alloc;
use alloc::vec::Vec;
use alloc::boxed::Box;
pub trait ConnectionImp {
    fn send_data(&self);
}

pub struct Collector {
    pub connections: Vec<Box<dyn ConnectionImp>>
}

impl Collector {
    pub fn new() -> Collector {
        Collector {
            connections: Vec::with_capacity(5),
        }
    }
    pub fn add_connection(&mut self,conn: Box<dyn ConnectionImp> ){
        self.connections.push(conn);
    }
}

我尝试使用 heapless crate,但找不到 Box 的替代品。以下代码显示了我的努力结果:

use heapless::{Vec,/*pool::Box*/};
extern crate alloc;

use alloc::boxed::Box;

pub trait ConnectionImp {
    fn send_data(&self);
}

pub struct Collector {
    pub connections: Vec<Box<dyn ConnectionImp>,5>
}

impl Collector {
    pub fn new() -> Collector {
        Collector {
            connections: Vec::new(),
        }
    }

    pub fn add_connection(&mut self, conn: Box<dyn ConnectionImp> ){
        self.connections.push(conn);
    }
}

是的,您可以使用 &dyn Trait。很多动态调度的例子使用 Box 因为它是一个更常见的用例并且使用引用引入了生命周期,这往往会使例子更复杂。

您的代码将变为:

pub struct Collector<'a> {
    pub connections: Vec<&'a dyn ConnectionImp>,
}

impl<'a> Collector<'a> {
    pub fn new() -> Collector<'a> {
        Collector {
            connections: Vec::new(),
        }
    }

    pub fn add_connection(&mut self, conn: &'a dyn ConnectionImp) {
        self.connections.push(conn);
    }
}