有什么办法可以转换Box<Box<Foo + Send>>到 Box<Box<Foo>? [英] Is there any way to convert Box&lt;Box&lt;Foo + Send&gt;&gt; to Box&lt;Box&lt;Foo&gt;&gt;?

查看:42
本文介绍了有什么办法可以转换Box<Box<Foo + Send>>到 Box<Box<Foo>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这样的代码:

trait Foo {
    fn foo(&self);
}

fn consume_func(b: Box<Box<Foo>>) {
    unimplemented!();
}

fn produce_func() -> Box<Box<Foo + Send>> {
    unimplemented!();
}

fn main() {
    let b = produce_func();
    consume_func(b);
}

它不编译:

error[E0308]: mismatched types
  --> src/main.rs:24:18
   |
24 |     consume_func(b);
   |                  ^ expected trait `Foo`, found trait `Foo + std::marker::Send`
   |
   = note: expected type `std::boxed::Box<std::boxed::Box<Foo + 'static>>`
              found type `std::boxed::Box<std::boxed::Box<Foo + std::marker::Send>>`

Box一种给C库一个void * 来自 Box 的指针.由于胖指针,我无法将 Box 转换为 void *.

The double Box is a way to give a C library a void * pointer from Box<Trait>. Because of fat pointers, I can not convert Box<Foo> to void *.

我不能改变 consume_func,我宁愿不使用 unsafe 或额外的分配.

I can not change consume_func, and I'd prefer to not use unsafe or additional allocation.

推荐答案

虽然你已经声明你不能改变 consume_func,但其他有类似问题的人可以改变它以接受泛型:

Although you've stated you cannot change consume_func, others with similar issues can change it to accept a generic:

fn consume_func<F: Foo + ?Sized>(b: Box<Box<F>>) {
    unimplemented!();
}

这篇关于有什么办法可以转换Box<Box<Foo + Send>>到 Box<Box<Foo>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆