rust - 特征边界 `std::io::Write + ' static: std::marker::Sized` 不满足,当传递闭包时

标签 rust traits higher-order-functions

我试图摆脱我程序中的一些代码重复,我决定使用一个函数,该函数将采用 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 新手,没能找到解决方案。

最佳答案

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

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

关于rust - 特征边界 `std::io::Write + ' static: std::marker::Sized` 不满足,当传递闭包时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37251254/

相关文章:

rust - 使用wasm-pack构建Rust代码时如何解决 "#error Unsupported architecture"?

generics - 如何实现 From 将一种结果类型转换为另一种结果类型?

javascript - Array.reduce 中的参数名称应该是什么?

haskell - 像这样写下 foldlM 的定义需要什么样的知识或培训?

multithreading - rust : borrowed value does not live long enough 中的生命周期问题

rust - Rust 是如何编译成机器码的?

recursion - 使用 impl trait 返回递归迭代器时溢出评估需求

swiftmailer - Swiftmailer 的 Silex 特征。 fatal error :调用未定义的方法 Silex\Application::mail()

groovy - CodeNarc是否可以使用Groovy特性?

c++ - 使用函数属性构造 qi::rule