T
T
Tolik2017-07-17 22:10:11
Rust
Tolik, 2017-07-17 22:10:11

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,
        }
    }
}

I get an error when compiling
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#E0118
Of course, I don't need such a function at all, but it is just an example of what I want to do.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Kolesnichenko, 2017-07-18
@Diel

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,
        }
    }
}

2. In general, it is better to use ordinary functions:
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 question

Ask a Question

731 491 924 answers to any question