rust - 无法实现自定义特征的 io::Read

标签 rust traits

我想为我的自定义特征实现 std::io::Read 特征。这是我的尝试:-

use std::io::Read;

trait Bar {
    fn foo(&self);
}

impl<T: Bar> Read for T {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        Ok(0)
    }
}

Playground

错误:-

   Compiling playground v0.0.1 (/playground)
error[E0119]: conflicting implementations of trait `std::io::Read` for type `&mut _`:
 --> src/lib.rs:7:1
  |
7 | impl<T: Bar> Read for T {
  | ^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: conflicting implementation in crate `std`:
          - impl<R> std::io::Read for &mut R
            where R: std::io::Read, R: ?Sized;
  = note: downstream crates may implement trait `Bar` for type `&mut _`

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
 --> src/lib.rs:7:6
  |
7 | impl<T: Bar> Read for T {
  |      ^ type parameter `T` must be used as the type parameter for some local type
  |
  = note: implementing a foreign trait is only possible if at least one of the types for which is it implemented is local
  = note: only traits defined in the current crate can be implemented for a type parameter

error: aborting due to 2 previous errors

最佳答案

目前不允许这样做,如注释中所述:

= note: downstream crates may implement trait `Bar` for type `&mut _`

您正在尝试为所有实现 Bar 的类型实现 Read,但您不能保证 Bar 的所有实现(目前或将来)现在还没有或不会实现Read。例如,您的 crate 的用户可能会为他们自己的类型之一实现 Bar

第二个错误中解释了另一个问题:

= note: implementing a foreign trait is only possible if at least one of the types for which is it implemented is local
= note: only traits defined in the current crate can be implemented for a type parameter

仅当您的包中定义了特征(Read 未定义)或类型时,您才可以实现该特征您要实现它的目的是在您的箱子中定义的。这意味着您无法为 T 实现 Read,因为 T 实际上是任何类型,包括来自其他 crate 。

解决此问题的方法是添加一个函数,该函数从任意 T: Bar 公开 Read 实现:

use std::io::Read;

trait Bar {
    fn foo(&self);
    fn as_reader(&self) -> BarRead<&Self> {
        BarRead(self)
    }
}

pub struct BarRead<T>(T);

impl<T: Bar> Read for BarRead<T> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        Ok(0)
    }
}

关于rust - 无法实现自定义特征的 io::Read,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65168386/

相关文章:

shell - 如何执行参数中带引号的命令?

rust - 如何使用 serde 和 bincode 映射填充超过 32 字节的 C 结构?

rust - 为什么 impl trait 不能用于返回多个/条件类型?

scala - 将特征视为另一个类的子类

module - 看不懂 Rust 模块系统

error-handling - 当 String 可以立即在 stdout 中报告时,它是否是有效的错误类型?

rust - 从 Cranelift 发出 ASM

pattern-matching - 匹配实现特征并因此返回它的类型

scala - 超越特质和 self 类型

scala - 如何在 Scala 中定义 HKT for instance (over object) 方法?