Impl generic on associated type

Hello,

I want to implement the From trait on an associated error type of embedded-hal.
I know the syntax if you have also a second generic:

    impl<SPI, CS, SpiError, IoError> Display<SPI, CS>
        where
            SPI: hal::blocking::spi::Write<u8, Error = SpiError>,
            CS: hal::digital::v2::OutputPin<Error = IoError>,
    {
        ...
    }

But I have no Idea how to get the <Error = SpiError> part if i don't wan the other generics or are not allowed to have them because the compiler yells at me:

    impl<PIN, E> From<E> for () 
        where 
            PIN: hal::digital::v2::OutputPin<Error = E>
    {
        fn from(err: E) -> Self {
            Err(());
        }
    }

In your case the compiler can't infer from which trait the associated Error is, so the correct syntax would be:

impl<PIN, E> From<E> for () 
where 
    <PIN as TraitWithError>::Error = E,
{
    fn from(err: E) -> Self {
        Err(());
    }
}

However, you dont't mention PIN in the impl, therefore the compiler won't do this anyway.

Yes, that is exactly my problem. I only added PIN because the compiler complained or I don't know how else to write it that E is the associated type.
So I want to get rid of PIN but I don't know how.
I tried this to no avail:

impl<E> From<E> for ()
where
    E: hal::digital::v2::OutputPin::Error
{
    fn from(err: E) -> Self {
        ()
    }
}

Then I get that hal::digital::v2::OutputPin::Error is not a trait (which is correct but doesn't help me)

Okay now I get a bit closer to what you want to achieve :thinking:.

But what is it what you realy want? You try to implement From<SomeError> for () this means that you want to create a () from a error. I simply can't see the gain of this.

In the end, you will have to find the concrete Error your impl of OutputPin uses and do the implementation for this concrete type. But be aware of the orphan rules of Rust you can't implement traits for types that don't belong to your crate.

Well I just used () as placeholder for my own Error type because I thought that is unecessary detail.
My version looked like this:

impl<E> From<E> for DisplayError
where
    E: hal::digital::v2::OutputPin::Error
{
    fn from(err: E) -> Self {
        DisplayError::PinError(err)
    }
}

I use this because I am also using SPI which gives a different Error which I also want to be able to pass on

I recently had this same issue trying to pass on all possible PIN errors (for each pin used) in the max7219 driver but I couldn't figure it out either. I just "ate" all error types into my PinError without providing the details of what actually happened as a workaround for now.

If you do figure this out I'll use it as well.

To me it looks like you want to be adding to the where;

(): From<IoError>,

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.