gpt4 book ai didi

generics - Rust:为什么不存储类型时泛型会继承大小大小?

转载 作者:行者123 更新时间:2023-12-03 11:41:52 25 4
gpt4 key购买 nike

我试图在第二个结构中存储对特征的引用。特质应该实现一个更高级的特质,我想用它来调用专用特质上的函数。
我如何告诉Rust我的T内部的特征Box实现了我想调用的特征,即使它是组合特征也是如此?
我也试过了

impl<T: 'static> Storage<T>
where
T: DerefMut<Target=dyn ToBeCalled>,
{
然后,我有2个不同的 Dyn特征,我找不到方法来强制转换它们。这可能会导致如何在 rust 内部处理 vtables产生问题。

我的程序中有以下代码(散布了一些结构和特征,但是此代码段导致了相同的编译器错误)。
use core::ops::DerefMut;

pub trait ToBeCalled {
fn to_call(&mut self);
}
pub trait MoreAdvanced : ToBeCalled
{
fn something_else(&mut self);
}

struct MoreAdvancedImpl
{
}

impl MoreAdvanced for MoreAdvancedImpl
{
fn something_else(&mut self) {}
}

impl ToBeCalled for MoreAdvancedImpl
{
fn to_call(&mut self) {}
}

pub struct Storage<T> {
pub store: T,
}

impl<T: 'static, U> Storage<T>
where
T: DerefMut<Target=U>,
U: ToBeCalled, //Why must U be sized here?
{
pub fn new(store: T) -> Self {
Storage {
store,
}
}
pub fn call_high_level_function(&mut self)
{
self.store.to_call();
}
}

fn main()
{
let mai = MoreAdvancedImpl{};
let a : Box<dyn MoreAdvanced> = Box::new(mai);
//let a = Box::new(mai); // This works, but here the size is not "hidden" by the trait
let _b = Storage::new(a);
}
编译输出:
error[E0277]: the size for values of type `dyn MoreAdvanced` cannot be known at compilation time
--> src/main.rs:46:27
|
20 | pub fn new(store: T) -> Self {
| ---------------------------- required by `Storage::<T>::new`
...
46 | let _b = Storage::new(a);
| ^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn MoreAdvanced`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>

最佳答案

默认情况下,Sized是隐含的。要选择退出此行为,可以使用?SizedRust docs提及:

All type parameters have an implicit bound of Sized. The special syntax ?Sized can be used to remove this bound if it's not appropriate.


Rust Book中对此有更多信息:
  • The Rust Programming Language, "Dynamically Sized Types and the Sized Trait"
  • 关于generics - Rust:为什么不存储类型时泛型会继承大小大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62620193/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com