gpt4 book ai didi

rust - 无法实现io::Read以获得自定义特征

转载 作者:行者123 更新时间:2023-12-03 11:34:55 26 4
gpt4 key购买 nike

我想为我的自定义特征实现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 _`
您正在尝试为实现 Read的所有类型实现 Bar,但是不能保证 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
仅当在 crate 中定义了特征(未指定 Read)或在 crate 中定义了要实现其特征的类型时,才可以实现该特征。这意味着您不能为 Read实现 T,因为 T实际上是任何类型,包括来自其他 crate 的任意类型。
一种解决方法是添加一个函数,该函数从任意 Read中公开 T: Bar实现:
use std::io::Read;

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

pub struct BarRead<T>(T);

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com