【问题标题】:Is there a heapless trait object?是否有无堆特征对象?
【发布时间】: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);
    }
}

【问题讨论】:

  • 是的,您可以使用&amp;dyn ConnectionImp

标签: rust trait-objects


【解决方案1】:

是的,您可以使用&amp;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);
    }
}

【讨论】:

  • 太棒了!非常感谢
  • @pejman.ghd 原始指针和对特征对象的可变引用也是允许的,以及具有?Sized 绑定的任何泛型类型。
猜你喜欢
  • 2013-05-31
  • 2019-05-28
  • 2019-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多