Need help with unconstrained type parameter

Consider this contrived example

enum Result<T, E> 
where 
    T: Into<Option<()>>,
    E: Into<Option<()>>
{
    Ok(T),
    Err(E)
}

trait Generic<T, E>
where 
    T: Into<Option<()>>,
    E: Into<Option<()>>
{
    fn generic (&self) -> Result<T, E>;
}

trait GetResult {
    fn getResult (&self) -> Option<()>;
}

impl<T, E, G, U> GetResult for (G, Option<()>)
where G: Generic<T, E>
{
    fn getResult (&self) -> Option<()> {
        self.0.into()
    }
}

playground link

really straightforward i want to the trait implementations of Generic to be able to return a type than can be converted into Option<()> rather than Option<()> itself and i need to use that trait in another trait implementation.

but i get

Error[E0207]: the type parameter `E` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:22:9
   |```

You can use associated types in Generic rather than generic type parameters. Not sure if that fits your real use case or not, but it's an option.

I had to change getResult impl to something of my own imagination since self.0.into() is incorrect - we need to pick either T or E to convert to the Option<()>.

enum Result<T, E> 
where 
    T: Into<Option<()>>,
    E: Into<Option<()>>
{
    Ok(T),
    Err(E)
}

trait Generic
{
    type T: Into<Option<()>>;
    type E: Into<Option<()>>;
    
    fn generic (&self) -> Result<Self::T, Self::E>;
}

trait GetResult {
    fn getResult (&self) -> Option<()>;
}

impl<T, E, G> GetResult for (G, Option<()>)
where
    G: Generic<T=T, E=E>,
    T: Into<Option<()>>,
    E: Into<Option<()>>
{
    fn getResult (&self) -> Option<()> {
        match self.0.generic() {
            Result::Ok(e) => e.into(),
            Result::Err(e) => e.into()
        }
    }
}

fn main() {
}

playground

2 Likes

amazing help as usual. thanks a lot!