创建具有多个类型范围的盒子

时间:2019-04-24 12:37:12

标签: rust

因为无法返回其他类型(请参见Why can impl trait not be used to return multiple / conditional types?),我想使用Box

但是我的案子需要实现多个特征。

use std::fs::File;
use std::io::{Cursor, Read, Seek};

fn foo(condition: bool) -> Box<Read + Seek> {
    if condition {
        Box::new(File::open("/etc/passwd").unwrap())
    } else {
        Box::new(Cursor::new(vec![1, 2, 3, 4]))
    }
}

结果

error[E0225]: only auto traits can be used as additional traits in a trait object
 --> src/lib.rs:4:39
  |
4 | fn foo(condition: bool) -> Box<Read + Seek> {
  |                                       ^^^^ non-auto additional trait

error: aborting due to previous error

For more information about this error, try `rustc --explain E0225`.

rustc --explain E0225给我:

  

您试图使用多种类型作为闭包或特征对象的界限。   Rust目前不支持此功能。导致此错误的简单示例:

fn main() {
    let _: Box<dyn std::io::Read + std::io::Write>;
}
     

自动特征(例如发送和同步)是该规则的例外:   可能有一个非内置特征的界限,加上任意数量的   汽车特质。例如,以下代码可以正确编译:

fn main() {
    let _: Box<dyn std::io::Read + Send + Sync>;
}

尽管声明,“ Rust当前不支持此功能” ,是否有解决方法?

0 个答案:

没有答案