如何编写具有动态泛型的结构?

发布于 2025-01-11 17:50:35 字数 500 浏览 1 评论 0原文

假设我有以下结构,

trait T{}
struct A<X:T>{
    ...
}

我想知道这样的事情是否可能

Box<A<dyn T>>

当前我收到错误

the trait `Sized` is not implemented for `(dyn T + 'static)`

,但是当我添加时

trait T:Sized{}

我得到

the trait cannot be made into an object because it requires `Self: Sized`

Let's say I have the following struct

trait T{}
struct A<X:T>{
    ...
}

I'm wondering whether something like this is possible

Box<A<dyn T>>

Currently I get errors

the trait `Sized` is not implemented for `(dyn T + 'static)`

but when I add

trait T:Sized{}

I get

the trait cannot be made into an object because it requires `Self: Sized`

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的笑 2025-01-18 17:50:35

这是可能的,但泛型默认具有 Sized 绑定,这会阻止它们被未调整大小的特征对象实例化。您需要指定 T: ?Sized

trait T {}
struct A<X: ?Sized + T> {}

例如:

trait T {}
impl T for () {}

struct A<X: ?Sized + T> {
    value: X,
}

fn foo() {
    let _ = Box::<A<()>>::new(A { value: () }) as Box<A<dyn T>>;
}

游乐场

It is possible, but generics have the Sized bound by default, which prevents them from being instantiated by a trait object, which is unsized. You need to specify T: ?Sized:

trait T {}
struct A<X: ?Sized + T> {}

E.g.:

trait T {}
impl T for () {}

struct A<X: ?Sized + T> {
    value: X,
}

fn foo() {
    let _ = Box::<A<()>>::new(A { value: () }) as Box<A<dyn T>>;
}

Playground.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文