【发布时间】:2021-07-29 18:46:36
【问题描述】:
有没有办法完全在堆栈内存中实现特征对象?
这是我使用 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 ConnectionImp。
标签: rust trait-objects