Potatoman
Potatoman

Reputation: 35

Add trait to extend builtin types

I'm trying to extend the Iterator trait with a custom function:

pub trait CustomTrait<T> : Iterator<Item=T> where Self: Sized, Self: 'static {
    #[inline]
    fn custom_function(self) -> Result<Box<dyn Iterator>, Err> {
        let boxed = Box::new(self);
        do_something(boxed)
    }
}

It's compiles correctly. However, when I go to call my new trait on a iterator, the compiler complains about it not being implemented for the iterator. (I have tried std::ops::Range and std::slice::Iter<'_, {integer}>.)

I was able to get each function call working for individual struct types with lines such as below:

impl CustomTrait<u64> for std::ops::Range<u64> {}

However, I assume there must be a way that I can get my trait definition to apply to all Iterables without having to manually implement it for each struct that implements the Iterable trait.

Upvotes: 3

Views: 930

Answers (1)

cadolphs
cadolphs

Reputation: 9637

When you extend a trait, you basically create a new trait that also guarantees that it has all the methods defined by the trait it's extending.

What it not does is automatically implement any of those methods for the trait you're extending.

In addition to what you already did, you actually need to implement your trait for Iterator:

impl<T> CustomTrait<T> for Iterator<Item=T> {
  ...
}

Upvotes: 4

Related Questions