【问题标题】:the trait bound `std::io::Write + 'static: std::marker::Sized` is not satisfied, when passing closure传递闭包时,不满足特征绑定`std::io::Write +'static:std::marker::Sized`
【发布时间】:2016-09-12 02:03:23
【问题描述】:

我正在尝试摆脱程序中的一些代码重复,我决定使用一个函数,该函数将采用 Fn() -> Result<io::Write> 类型的闭包,当我要求它时将为我提供一个输出流。

所以这是这个函数:

fn dowload_body<F>(/* some params ommited */ write_supplier: F) -> Result<()>
  where F: Fn() -> Result<Write> {
  if ... {
    let mut destination = try!(write_supplier());
    // use this stream
  }
}

我想像这样使用它:

let destination_path = Path::new("some path");
let result = Self::dowload_body(|| try_str!(OpenOptions::new().append(true).open(destination_path)));

我收到以下错误:

src/http.rs:105:3: 121:4 error: the trait bound `std::io::Write + 'static: std::marker::Sized` is not satisfied [E0277]
src/http.rs:105   fn dowload_body<F>(write_supplier: F) -> Result<()>
                  ^

我是 rust 新手,没有找到解决方案。

【问题讨论】:

    标签: rust traits higher-order-functions


    【解决方案1】:

    您不能将未调整大小的变量(特征)直接放在结果中。也许你是这个意思?

    fn dowload_body<F, W: Write>(write_supplier: F) -> Result<()>
    //                 ^
      where F: Fn() -> Result<W> 
    //                        ^ create a template for the trait.
    {
    

    【讨论】:

    • 谢谢你,这有帮助。所以我知道我总是必须返回一个具体类型,而 trait ofc 不是,所以我需要为任何实现 Write 特征的具体类型 W 构建一个模板。我说的对吗?
    • @Łukasz 对。或者,您可以使用特征对象,例如Box&lt;Write&gt;,但这需要动态调度(更多间接)
    猜你喜欢
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2022-11-30
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多