pej*_*man 4 rust trait-objects
有没有办法在堆栈内存中完全实现 trait 对象?
这是我使用的代码,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);
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用无堆板条箱,但找不到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);
}
}
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用&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);
}
}
Run Code Online (Sandbox Code Playgroud)