为什么 Rust 编译器不认为 Box<FileRotate<_>> 是 Box<(dyn std::io::Write + Send + 'static) 的有效实现?

Why Rust compiler doesn't consider Box<FileRotate<_>> as valid a implementation for Box<(dyn std::io::Write + Send + 'static)?

我试图通过将盒装 FileRotate 实例(来自 file-rotate 板条箱)与 fern [=20= 链接起来,将旋转日志与 fern 结合起来] 实例,但似乎无法满足编译器的要求。这是代码片段:

let log= Box::new(
    FileRotate::new(
        "log/output.log",
        CountSuffix::new(2),
        ContentLimit::Lines(10),
        Compression::None));

fern::Dispatch::new()
    .level(LevelFilter::Debug)
    .chain(log)
    .apply()?;

编译器不同意,出现以下错误:

error[E0277]: the trait bound `fern::Output: From<Box<FileRotate<CountSuffix>>>` is not satisfied
   --> src/main.rs:101:16
    |
101 |         .chain(log)
    |          ----- ^^^ the trait `From<Box<FileRotate<CountSuffix>>>` is not implemented for `fern::Output`
    |          |
    |          required by a bound introduced by this call
    |
    = help: the following implementations were found:
              <fern::Output as From<&'static (dyn log::Log + 'static)>>
              <fern::Output as From<Box<(dyn log::Log + 'static)>>>
              <fern::Output as From<Box<(dyn std::io::Write + Send + 'static)>>>
              <fern::Output as From<Dispatch>>
            and 6 others
    = note: required because of the requirements on the impl of `Into<fern::Output>` for `Box<FileRotate<CountSuffix>>`
note: required by a bound in `Dispatch::chain`
   --> /Users/l203663/.cargo/registry/src/github.com-1ecc6299db9ec823/fern-0.6.0/src/builders.rs:195:21
    |
195 |     pub fn chain<T: Into<Output>>(mut self, logger: T) -> Self {
    |                     ^^^^^^^^^^^^ required by this bound in `Dispatch::chain`

但是,FileRotate 结构同时实现了 WriteSend,如记录 here and here

编译器建议的最接近的实现是 IMO:

From<Box<(dyn std::io::Write + Send + 'static)>>

正在使用的板条箱:

log = "0.4.14"
fern = "0.6.0"
file-rotate = "0.5.3" 

我不确定这就是所有问题(没有使用 fern)但是由于 chain() 的输入参数是通用的,它不会自动强制您的 Box<FileRotate>Box<dyn Write + Send>,所以你必须明确地这样做:

.chain(log as Box<dyn Write + Send>)

您不需要指定 'static,因为这是所有 Box<dyn ...>(但不是 &dyn ...)的默认值。