[英]Box like container FixedSizeBox<128, dyn SomeTrait> which can be constructed from type implementing SomeTrait
I would like to implement a FixedSizeBox
which behaves like the Box
but owns the memory in which the object is stored.我想实现一个
FixedSizeBox
,它的行为类似于Box
但拥有 memory ,其中存储了 object 。 I introduced an additional paramater CAPACITY
which defines the size of the memory which the FixedSizeBox
will own.我介绍了一个额外的参数
CAPACITY
,它定义了FixedSizeBox
将拥有的 memory 的大小。 The problem I encounter is that I am unable to use dyn SomeTrait
as FixedSizeBox
type and call new
with a specific type.我遇到的问题是我无法使用
dyn SomeTrait
作为FixedSizeBox
类型并使用特定类型调用new
。
Let's assume I have a trait SomeTrait
and a struct A
which implements that trait.假设我有一个特征
SomeTrait
和一个实现该特征的结构A
。
trait SomeTrait {}
struct A(u8);
impl SomeTrait for A {}
When I would like to store any object which implements SomeTrait
in a Box
I can write当我想在一个
Box
中存储任何实现SomeTrait
的 object 时,我可以写
let mut a: Box<dyn SomeTrait>;
a = Box::new(A { 0: 0 });
For the FixedSizeBox
I would like to have the same functionality and implemented it like:对于
FixedSizeBox
我希望具有相同的功能并像这样实现它:
pub struct FixedSizeBox<const CAPACITY: usize, T: ?Sized> {
_marker: PhantomData<T>,
}
impl<const CAPACITY: usize, T> FixedSizeBox<CAPACITY, T> {
pub fn new(_: T) -> FixedSizeBox<CAPACITY, T> {
FixedSizeBox::<CAPACITY, T> {
_marker: PhantomData,
}
}
}
When I use it in the same fashion as the Box
the compiler fails:当我以与
Box
相同的方式使用它时,编译器会失败:
let mut b: StackBox<128, dyn SomeTrait>;
// assigning a specific type leads to
// mismatched types
// expected struct `StackBox<dyn SomeTrait, 128_usize>`
// found struct `StackBox<A, {_: usize}>` (rustc E0308)
b = StackBox::new(A { 0: 0 });
I looked into the Box
and Rc
implementations but was unable to figure out how rust actually realized this.我查看了
Box
和Rc
的实现,但无法弄清楚 rust 是如何实现这一点的。 Is there some trait missing?是不是缺少什么特质?
As a side constraint, I would like to use stable rust.作为附带限制,我想使用稳定的 rust。 I could figure out that the nightly feature
CoerceUnsized
我可以弄清楚夜间功能
CoerceUnsized
impl<T, U> std::ops::CoerceUnsized<StackBox<U>> for FixedSizeBox<T>
where
T: std::marker::Unsize<U> + ?Sized,
U: ?Sized,
{
}
solves the issue but I would like to understand how this is realized in stable rust for Box
so that I can apply it to the FixedSizeBox
.解决了这个问题,但我想了解这是如何在稳定的 rust for
Box
中实现的,以便我可以将其应用于FixedSizeBox
。
Box
is in the standard library, and as such it is allowed to use nightly features even on stable versions. Box
在标准库中,因此即使在稳定版本上也可以使用夜间功能。 You cannot do that without nightly.如果没有 nightly,你就无法做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.