Answer the question
In order to leave comments, you need to log in
How to automatically implement certain methods for all types that implement a certain trait?
For example, I want to make a read_one_byte method for all types for which an impl Read is made. The code looks like this:
impl<T: Write> T {
fn read_one_byte(&self) -> Option<u8> {
let mut buf = [0u8];
match self.read(&mut buf) {
Ok(count) if count == 1 => Some(buf[0]),
_ => None,
}
}
}
error[E0118]: no base type found for inherent implementation
--> src/main.rs:4:16
|
4 | impl<T: Write> T {
| ^ impl requires a base type
|
= note: either implement a trait on it or create a newtype to wrap it instead
https://doc.rust-lang.org/error-index.html#E0118Answer the question
In order to leave comments, you need to log in
1. You can create a new trait that will extend the standard one:
use std::io::Read;
trait ReadOneByte: Read {
fn read_one_byte(&mut self) -> Option<u8>;
}
impl<T: Read> ReadOneByte for T {
fn read_one_byte(&mut self) -> Option<u8> {
let mut buf = [0u8];
match self.read(&mut buf) {
Ok(count) if count == 1 => Some(buf[0]),
_ => None,
}
}
}
fn read_one_byte<T: Read>(source: &mut T) -> Option<u8> {
let mut buf = [0u8];
match self.read(&mut buf) {
Ok(count) if count == 1 => Some(buf[0]),
_ => None,
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question